在JavaScript中访问Ajax POST响应 [英] Accessing ajax POST response in javascript
问题描述
我正在通过JavaScript函数发出Ajax POST请求:
I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
从我的处理程序中,我要发送带有以下内容的json字符串:
From my handler, I'm sending json string with:
context.Response.write(json);
我想我会在msg
中得到它.
I think I'll get it in msg
.
我也想发送其他字符串(计数).所以我正在尝试将标头信息与json数据一起使用.所以我添加了这一行:
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
如果这是正确的方法,该如何在我的success
函数中访问它?
If this is right way to do it, how can I access it in my success
function?
推荐答案
要访问success
函数中的标头,请在函数中再添加2个参数,状态码和jqXHR对象,您可以阅读文档用于 api.jquery.com .
To access headers in your success
function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
因此,您的函数应如下所示:
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
但是,正如注释中指出的那样,最好不要使用标头发送数据.您应该只将其包含在您发送的json中.
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
您还需要告诉jQuery通过设置将响应解释为json
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
否则,它将作为文本返回给您.
Otherwise, it will just be returned to you as text.
这篇关于在JavaScript中访问Ajax POST响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!