我正在尝试使用Ajax发布请求发送纯字符串:
var user = {
"name": name,
"country": country,
};
$.ajax({
type: 'POST',
traditional: true,
url: 'Default.aspx/Submit',
data: JSON.stringify(user),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (msg) {
alert("Success!");
},
error: function () {
alert("Error!");
}
});
[WebMethod]
public static bool Submit(string json)
{
// do something
return true;
}
我设置:
string
,而非object
text
而非json
但我仍然从服务器收到此错误:
无效的Web服务调用,缺少参数值:json
我想这是因为它找不到“json”参数的匹配名称。但我不明白如果我发送一个普通字符串,我必须如何命名函数参数。
答案 0 :(得分:2)
这是我用来使用AJAX发布到数据库的代码。
//保存请求的变量 var request;
//绑定到表单的提交事件 $("#form1中&#34)。提交(函数(事件){
// Abort any pending request
if (request) {
request.abort();
}
//local variables
var $form = $(this);
// select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to php file
request = $.ajax({
url: yourdomain-asp-page,
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
//replace form with feedback text
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
// Prevent default posting of form
event.preventDefault();
});