小编典典

如何在$ ajax POST中传递参数?

ajax

我已经按照链接中所述的教程进行操作。在下面的代码中,由于某种原因,数据不会作为参数附加到url上,但是如果我使用/?field1="hello"它直接将其设置为url
则可以。

$.ajax({
        url: 'superman',
        type: 'POST',
        data: { field1: "hello", field2 : "hello2"} ,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            alert(response.status);
        },
        error: function () {
            alert("error");
        }
    });

阅读 1273

收藏
2020-07-26

共1个答案

小编典典

对于简单的情况,我建议您使用jQuery
$.post$.get语法:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
});

如果您需要捕获失败案例,请执行以下操作:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});

此外,如果您始终发送JSON字符串,则可以在最后使用$
.getJSON
或$
.post以及另一个参数。

$.post('superman', { field1: "hello", field2 : "hello2"}, 
     function(returnedData){
        console.log(returnedData);
}, 'json');
2020-07-26