如何获取POST方法“$.POST()”的结果

How to get result of POST method `$.post()`?

本文关键字:POST 结果 方法 获取 何获取      更新时间:2023-09-26

我使用以下代码来POST数据:

$.post("http://domain/page.aspx", postdata);

更新:

以下代码不起作用:

$.post("http://domain/page.aspx", postdata, function(data){alert(data);});

如何获得字符串形式的服务器响应?

我预计您遇到的是同源策略,该策略防止ajax跨源发布,除非服务器上支持并配置CORS以允许来自页面源的请求(并且正在使用的浏览器支持它)。

使用回调函数

$.post("http://domain/page.aspx", postdata, function(result) {
    alert(result);
    $('divID').html(result);
});

来自您的评论

好的,我理解。当我在POST后面放置警报时,它具有"panding"状态。如果我删除警报,页面将发生变化(很难停止)。重定向前POST的状态为"已取消"

我知道你在点击某个链接后拨打了.post电话。您需要取消单击事件,这样链接就不会被关注。

所以如果你有一些像这样的代码

$('a').click(function(){
  $.post("http://domain/page.aspx", postdata, function(data){alert(data);});
});

将其更改为

$('a').click(function(e){ // added e as parameter which get the event
  e.preventDefault(); // added this line which cancels the default action of the click
  $.post("http://domain/page.aspx", postdata, function(data){alert(data);});
});

$.post()在文档中有以下描述:

描述:使用HTTP POST请求从服务器加载数据。

 jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

其中,

url

    Type: String
    A string containing the URL to which the request is sent.

数据

    Type: PlainObject or String
    A plain object or string that is sent to the server with the request.

成功(数据,textStatus,jqXHR)

    Type: Function()
    A callback function that is executed if the request succeeds.
    dataType
    Type: String
    The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

所以,

$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");

返回JSON数据。因此,在那里使用dataType并相应地使用函数。