我是新手jquery ajax这里的代码我采用表单参数然后我希望它们以JSON格式解析..这是代码
function doAjaxPost() {
var name = $('#name').val();
var password = $('#password').val();
var gender = $('#gender').val();
var aboutYou = $('#aboutYou').val();
$.ajax({
type: "POST",
contentType:'application/json',
url: "add.htm",
dataType:'json',
data: "name=" + name + "&password=" + password + "&gender=" + gender + "&aboutYou=" + aboutYou,
success: function(data){
alert('name : '+name);
},
error: function(e){
alert('Error: ' + e);
}
});
}
这里我的问题是我没有以JSON格式获取数据,之后我必须将该JSON数据发送到控制器add.htm ....提前感谢
答案 0 :(得分:4)
错过了{}
将=
更改为:
data: {"name" : name , "password" : password , "gender" : gender , "aboutYou" : aboutYou}
答案 1 :(得分:1)
我个人使用JSON.Stringify。
function doAjaxPost() {
var name = $('#name').val();
var password = $('#password').val();
var gender = $('#gender').val();
var aboutYou = $('#aboutYou').val();
var parameters =
{
name: name,
password: password,
gender: gender,
aboutYou: aboutYou
};
$.ajax({
type: "POST",
contentType:'application/json',
url: "add.htm",
dataType:'json',
data: JSON.stringify(parameters),
success: function(data){
alert('name : '+name);
},
error: function(e){
alert('Error: ' + e);
}
});
}
答案 2 :(得分:1)
function doAjaxPost() {
var name = $('#name').val();
var password = $('#password').val();
var gender = $('#gender').val();
var aboutYou = $('#aboutYou').val();
$.ajax({
type: "POST",
contentType:'application/json',
url: "add.htm", // probably something like add.php!?
dataType:'json',
data: {
name: name,
password: password,
gender: gender,
aboutYou: aboutYou
},
success: function(data){
console.log('success', data);
alert('name : '+name); // this is probably wrong - you already know the name
},
error: function(e){
console.log('error', arguments[0], arguments[1], arguments[2]);
alert('Error: ' + e);
}
});
}
答案 3 :(得分:0)
你可以试试这个:
$.ajax({
type: "POST",
contentType:'application/json',
url: "add.htm",
dataType:'json',
data:{name:name,password:password,gender:gender,aboutYou:aboutYou},
success: function(data){
alert('name : '+name);
},
error: function(e){
alert('Error: ' + e);
}
});
您可以在服务器端检索参数..
答案 4 :(得分:0)
现在它的工作:)
function doAjaxPost() {
var name = $('#name').val();
var password = $('#password').val();
var gender = $('#gender').val();
var aboutYou = $('#aboutYou').val();
var your_data ={name: name ,password:password, gender: gender ,aboutYou: aboutYou};
$.ajax({
type: "POST",
contentType:'application/json',
url: "add.htm",
dataType:'json',
data:your_data ,
success: function(data){
alert('name : '+name);
},
error: function(e){
alert('Error: ' + e);
}
});
}