如何在 $ajax POST 中传递参数? [英] How to pass parameters in $ajax POST?

查看:62
本文介绍了如何在 $ajax POST 中传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have followed the tutorial as stated in this link. In the code below for some reason the data is not appended to the url as parameters, but if I set them directly to the url using /?field1="hello" it works.

$.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");
        }
    }); 

推荐答案

我建议你使用 $.post$.get 简单情况下的 jQuery 语法:

I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases:

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

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

If you need to catch the fail cases, just do this:

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

另外,如果你总是发送一个 JSON 字符串,你可以使用 $.getJSON 或 $.post 在最后多了一个参数.

Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.

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

这篇关于如何在 $ajax POST 中传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆