Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

javascript - Trailing spaces in Ajax response

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...