开发者

Why does the following JQuery Ajax call result in a script error in IE9?

I make the following JQuery(v1.5.1) Ajax call:

function testAjaxCall()
{
  $.ajax(
    {
        url: "/Search.ashx?",
        dataType: "json"
    });
}

This call returns the following JSON result:

{ "objectData" : "100" }

But in IE9 it fails with the following error (it works fine in other browsers):

SCRIPT1004: Expected ';' debug.finance.com, line 1 character 16

If I remove the dataType:json parame开发者_Python百科ter, the call succeeds. Any idea what is wrong? I assume my JSON is incorrect, but I passed it through a validator and it did not report any errors.

Please help!

EDIT: (more detail)

I output JSON from the server in an ASP.NET HTTP Handler as follows:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/json";
    context.Response.Write("{ \"objectData\" : \"100\" }");
    return;
}


Did you use JSON encoding in your server side script or did you just "build it" yourself?

When I first started fiddling with JSON I had wrongly assumed that you could just build a string of characters including curly and square brackets, colons and the like. It all looked fine when I examined XHR using the browser developer tools except what was being received was a string of characters not an object.

Then I learnt about the fact that you can just get your data on the server side, and use (for example in php) json_encode() to encode your data, and then you can use the JQUERY datatype JSON as you have done here, to parse the Javascript Object that is returned.

It's not exactly the same problem, but my question here should provide a bit more background information as to what's going on.


I figured out what the problem was thanks to this (slightly unrelated) post: jQuery 1.5 AJAX call fails with "invalid label" for JSON requests

The culprit was jquery.validate which was not 100% compatible with JQuery v1.5. As soon as I deleted it IE9 works perfectly!

I upgraded to jquery.validate v1.8 and everything is working beautifully now.


The underlying problem here is that IE9 doesn't support JSON over AJAX. Instead, for that browser, you need to use JSON-P.

See: JavaScript: How do I create JSONP?

On the client side, change dataType as follows:

// Fall back to JSON-P for IE9 and lower:
dataType: (('withCredentials' in new XMLHttpRequest ()) ? 'json' : 'jsonp'),        

On the server-side, just before you emit the JSON, do:

// In JSON-P mode, wrap the JSON with the callback name and brackets:
if (isSet ($_GET['callback']) && preg_match ('/^([_a-zA-Z0-9])$/', $_GET['callback']) ) {
    $json = $_GET['callback'] . '(' . $json . ');';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜