我想从ajax编辑返回的数据,然后返回使用ajax进行编辑的数据。
第一个AJAX请求成功,但第二个请求没有。我找不到什么问题。有帮助吗?
function first_func() {
return $.ajax({
url: "get_updated_data.php",
type: "POST",
dataType: "json",
data: {
original_data
},
})
}
function second_func(secondData) {
$.ajax({
url: "get_updated_data.php",
type: "POST",
data: {
edited_data
},
})
}
first_func().then(function(data) {
var NewData = data;
function editReturnedData() {
// edit first returned data here
}
return result;
}
second_func(secondData);
})
是否有任何理由将数据嵌入( edited_data
)?
在您的first_func
帖子中,您将数据发送为JSON。但不在您的second_func
帖子中。您的端点get_updated_data.php
?
jQuery post form-data(传统)
使用Post方法 default contentType 是'application/x-www-form-urlencoded; charset=UTF-8'
。因此,如果未指定其他 ContentType 您通常有两个选择:
- 查询 - 弦
- 对象(键Value)在发送 之前,该在内部通过jQuery转换为查询弦
请参阅文档jQuery ajax,"将数据发送到服务器"部分:
数据选项可以包含表单
key1=value1&key2=value2
的查询字符串,也可以包含表单{key1: 'value1', key2: 'value2'}
的对象的对象。如果使用后表单,则在发送jquery.param()之前将数据转换为查询字符串。可以通过将ProcessData设置为false来规避此处理。如果您希望将XML对象发送到服务器,则该处理可能是不希望的。在这种情况下,将ContentType选项从应用程序/X-WWW-Form-urlenCoded更改为更合适的MIME类型。
根据此,您应该称呼jQuery的ajax
函数如下:
var edited_data = "name=ravi&age=31"; // query string
// or
var edited_data = {name:"ravi",age:"31"}; // object (key-value pairs)
$.ajax({
url : "get_updated_data.php",
type: "POST",
data : edited_data,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
jQuery帖子数据作为JSON
您希望将数据发送为JSON和您的PHP-Endpoint所期望的。您的帖子需要以下调整:
-
dataType: 'JSON'
(来自您的 first_func ) -
data: JSON.stringify(data)
(来自您的 second_func ) -
contentType: 'application/json; charset=utf-8'
最佳选择是将其包裹在以下功能中:
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8', // header used by endpoint
data: JSON.stringify(data), // needed since JSON is sent in body as string
dataType: 'json', // this tells jQuery how to handle data-response
success: callback // this will be your callback-function
});
};
另请参见
- 用于简单的html形式发布:jquery ajax post示例php
- 用于发送JSON:jQuery-如何制作$ .post()使用contentType = application/json?