2012-04-19 110 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