Trailing spaces in Ajax response

十年热恋 提交于 2019-11-28 10:23:53

问题


I am trying to use Qunit to test some code, but I have some problems with Ajax calls. I cannot even get them to test correctly with the simplest Ajax call using jQuery methods. The problems seems to be that a trailing space is appended to the textResponse, no matter what I do.

My initial code was something like

asyncTest('Ajax calls', function() {
    expect(1);

    $.get('ajax.txt', {}, function(response) {
        equal(response, 'foo', 'Ajax calls work correctly');
    });

    setTimeout(function() {
        start();
    }, 600);
});

where ajax.txt is a text file containing olny the characters foo. This test fails, reporting

Ajax calls work correctly, expected: "foo" result: "foo ", diff: "foo" "foo "

I have then tried the following:

  • I have tested against "foo " (including a trailing space)
  • I have done response.replace(' ', '') before testing
  • I have varied the font encoding of the ajax.txt file
  • I have tested it both in Firefox and Chrome, each time cleaning the cache
  • I have manually tested for equality inside an alert, even with == comparison

but in no case I was able to get a match. For instance in the first variant I got the puzzling answer

Ajax calls work correctly, expected: "foo " result: "foo ", diff: "foo "

I am now going slightly mad. What could I have been possibly doing wrong?


回答1:


You can $.trim() (jQuery trim, since IE<9 doesn't have it natively) the result, like this:

equal($.trim(response), 'foo', 'Ajax calls work correctly');

Why is this happening? It's likely a formatting error, e.g. Unix vs Windows line endings that are creeping in there on you.




回答2:


I had similar - yes, very possibly line endings; I had to remove "\r" and "\n" to be sure it was working. The other way to get what you exopect is to use JSON. Get the AJAX call to return (e.g.)

{ "Text":"foo" }

Then test like:

equal(response.Text, 'foo', 'Ajax calls work correctly');

You need to set the AJAX return type to json in the jQuery AJAX call.



来源:https://stackoverflow.com/questions/4232264/trailing-spaces-in-ajax-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!