有効なJSONを返すaspxページがありますが、JQUERYを介して呼び出されると、FiddlerでJSONが返されるのに、エラーがスローされることがわかります[オブジェクトエラー]。
protected void Page_Load(object sender, EventArgs e)
{
string json = "{\"name\":\"Joe\"}";
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/json";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(json);
Response.End();
}
このページを使用しているhtmlページは別のドメインにあり、私はjsonpを使用しています。
function jsonpCallback(response){
alert(response.data);
}
$(document).ready(function(){
$.ajax({
url: 'http://localhost:30413/getprice.aspx',
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: jsonpCallback
});
});
aspxページが要求されると、有効なJSONがブラウザーに返され、JQUERY呼び出しが行われると、JSONが返されますが、コールバック関数は呼び出されず、予期される「;」JSエラーが発生すると、[オブジェクトエラー]メッセージが表示されます。以下は、行われた要求と応答です。
リクエストのすべてのバリエーションを試しましたが、同じ結果になりました。以下に示す最後のサンプルで機能するため、以下のリクエストJQUERYサンプルを使用しています。
GET http://localhost:30413/price.aspx?callback=jQuery17105556924406763212_1338876162569&_=1338876162581 HTTP/1.1
Accept: application/javascript, */*;q=0.8
Referer: http://alpha.tigerdirect.com/applications/b2b/varinfo.asp
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Accept-Encoding: gzip, deflate
Host: localhost:30413
Connection: Keep-Alive
Pragma: no-cache
Cookie: ASP.NET_SessionId=d4pje2hgm2beznslfpp4pii5
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 05 Jun 2012 06:02:42 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 14
Connection: Close
{"name":"Joe"}
このサンプルは機能します
function jsonpCallback(response){
alert(response.data);
}
$(document).ready(function(){
$.ajax({
url: 'http://api.bitbucket.org/1.0/repositories/retroviz/webformsthemeswitcher/src/tip/.hgignore',
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: jsonpCallback
});
});