如何获得POST方法`$ .post()的结果?

时间:2013-02-12 11:13:26

标签: javascript jquery

我使用以下代码来发布数据:

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

更新:

以下代码不起作用:

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

如何将服务器响应作为字符串?

4 个答案:

答案 0 :(得分:1)

使用回调功能

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

答案 1 :(得分:1)

我希望您在Same Origin Policy上运行,这会阻止ajax发布跨文章,除非在服务器上支持和配置CORS以允许来自您网页的请求origin(以及正在使用的浏览器支持它)。

答案 2 :(得分:1)

来自您的评论

  

好的,我明白了。当我在其后发出警报时,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);});
});

答案 3 :(得分:-1)

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

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

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

其中,

<强>网址

    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.

成功(data,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并相应地使用它。