2012-04-19 113 views
1

任何人都可以给我一个清晰的演练如何使用jsonp调用ashx处理程序或告诉我我做错了什么?我在一个子域上尝试调用另一个子域上的ashx处理程序的JavaScript函数。当我尝试返回200的状态,但它仍然进入我的错误处理并报告SyntaxError的thrownError:无效字符。我在jquery和jsonp上找到了一些线程,但只有一个实际上显示了与ashx相关的任何代码。不幸的是,它似乎没有工作,我不知道为什么。这里是javascript调用的代码,然后是ashx响应。使用jsonp与ashx处理程序

var sPay = getEl('chkPay').checked ? "pay=1" : ""; 
var sUrl = "/Calculator/GetCalcResult.ashx?jsoncallback=?" + sPay; 

$.getJSON(sUrl, function (data) { 
    console.log("Success:" + data); 
}).error(function (xhr, ajaxOptions, thrownError) { 
    console.log("Status:" + xhr.status); 
    console.log("Error:" + thrownError); 
}); 

然后是ashx的处理程序...

var jsonstr = 
       "{\"calculatorresults\":{" + 
        "\"employees\" : \"" + employeeCount + "\"" + 
        "\"pay\" : \"" + calculationResult.PayTotal + "\"" + 
        "\"total\" : \"" + calculationResult.Total + "\"" + 
       "}}"; 

      context.Response.ContentType = "application/json"; 
      context.Response.Write(string.Format("{0}({1});", context.Request["jsoncallback"], jsonstr)); 

回答

3

我最近与此挣扎以及....这里是我的解决方案的一个非常简化版本,包括基本需要的代码。

我试图将json传递到ashx页面并从该ashx页面检索json数据时遇到了跨域问题。在这个例子中,我发送一个SessionKey到ashx页面,并返回一个对象的ID。从客户端页面

JQuery的AJAX调用:

function CallASHXPage() 
{ 
    var strJson = '{ "Request": { "SessionKey": "ABCD-1234" } }'; 

    return $.ajax({ 
     url: "http://localhost:55724/RemoteJsonpTest.ashx?data=" + strJson, 
     cache: false, 
     crossDomain: true, 
     dataType: "jsonp" 
    }).done(function(data) 
    { 
     // handle the output here 
     alert(data.Response.OutputID); 
    }); 
} 

这里是ASHX页面上的代码:

// read in data param 
string JSON = context.Request.QueryString["data"]; 

// execute your ASHX code here 

// prepare resposne data 
string strResponse = "{\n"; 
strResponse += "\t\"Response\":\n"; 
strResponse += "\t{\n"; 
strResponse += "\t\t\"OutputID\": "12345"\n"; 
strResponse += "\t}\n"; 
strResponse += "}\n"; 

// output response wrapped in callback function 
string output = context.Request.Params["callback"]; 
output += "(" + strResponse + ");"; 
context.Response.Write(output); 
+0

缺少内容类型 – 2016-08-09 12:51:02