jquery - 将 jsonp 与 ashx 处理程序一起使用

标签 jquery jsonp ashx

任何人都可以给我一个关于如何使用 jsonp 调用 ashx 处理程序的清晰演练,或者告诉我我做错了什么?我在一个子域上有一个 javascript 函数,试图调用另一个子域上的 ashx 处理程序。当我尝试时,我得到了 200 的状态,但它仍然进入我的错误处理并报告 SyntaxError: Invalid character 的抛出错误。我在 jquery 和 jsonp 上找到了几个线程,但只有一个实际上显示了与 ashx 相关的任何代码。不幸的是它似乎不起作用,我不知道为什么。这是来自 javascript 调用的代码,然后是 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));

最佳答案

我最近也在解决这个问题......这是我的解决方案的一个非常简化的版本,其中包括基本的必要代码。

当我尝试将 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);

关于jquery - 将 jsonp 与 ashx 处理程序一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10237059/

相关文章:

php - 将部分高斯模糊应用于背景图像

javascript - 简单的 JS 执行但不做任何事情

javascript - 如何将文本添加到 JSON 的开头和结尾以使其成为 JSONP

jsonp - 在 Jersey Rest 中使用 @Consume 和 GET 请求

asp.net - 如何使用 ASP.NET 制作一个非常简单的 Web 代理?

javascript - 使用 animate.css 和 jquery 的顺序动画

javascript - js-jquery : prevent input from code injection

jsonp - 重命名 JSONP 的回调参数

asp.net - 通过调用.ashx页面下载文件

session - 如何防止 ashx 重置 session 超时?