我遵循了this链接中的教程.在下面的代码中,由于某种原因,数据不会作为参数附加到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");
        }
    }); 

推荐答案

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,最后再加一个参数.

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

Jquery相关问答推荐

try 使用jQuery AJAX将参数传递给http Post方法时出现未知错误

如何用each替换元素的attr href

Jquery如何通过数组中的属性查找对象

如何在 jQuery 中使用:not 和 hasClass() 来获取没有类的特定元素

如何使用jquery取消绑定所有事件

非 AJAX jQuery POST 请求

如何使用 jQuery Select 单个子元素?

如何在 Backbone.js - Backbone.sync 或 jQuery.ajax 中保存整个集合?

Select select2后触发动作

Onchange 通过 Select 打开 URL - jQuery

Jquery 和 HTML FormData 返回未捕获的 TypeError:非法调用

自动完成将值而不是标签应用于文本框

在不丢失光标位置的情况下更新输入值

使用 JQuery 激活 bootstrap 选项卡

获取没有在css中设置高度的div的高度

jQuery.active 函数

javascript,是否有像 isArray 这样的 isObject 函数?

带有 LIKE 的 Spring JPA @Query

是否可以将 async:false 设置为 $.getJSON 调用

如何使用 jQuery 的 form.serialize 但排除空字段