您现在的位置是:首页> 网站开发> jQuery> Ajax
Ajax中DATA传参的写法
- 5887人已阅读
- 时间:2018-10-16 08:56:34
- 分类:Ajax
第一种写法:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});第一种我们用url传参,参数里面如果加带"&"这个符号的话,可能参数接收不到或不完整,如“ data: "name=John&location=Boston",” 如果name的值是"john&smith"这样写可能就会有问题,我们可以用JS里面的encodeURIComponent()方法进行转义.
第二种写法:
$.ajax({
type: "POST",
url: "some.php",
data: {name:"John",location:"Boston"},
success: function(msg){
alert( "Data Saved: " + msg );
}
});这种不用转义了.
第三种写法:
$.ajax({
type: "POST",
url: "some.php",
data: {foo:["bar1", "bar2"]},
success: function(msg){
alert( "Data Saved: " + msg );
}
});其实转换为 '&foo=bar1&foo=bar2'
常用写法:
function addUser(){
var user = {
uname:$("#uname").val(),
mobileIpt:$("#mobileIpt").val(),
birthday:$("#birthday").val()
};
$.ajax({
url:'UserAdd.action',
data:user,
type:'post',
dataType:'text',
success:function(msg){
if(msg=='1'){
console.log('添加成功');
}else{
console.log('添加失败')
}
}
})
}function test(map){
$.ajax({
type : "POST",
url : url,
async:true,
dataType:'json',
data: map,
error : function(){},
success : function(data) {
.......
}
});
}
function test2(){
var id = $("#id").val(); //通过表单元素id取值。
var name = $("#name").val();
var map = "id="+id+" &name="+name; //参数之间用“&”隔开。这里注意连接符是用:“&” ,而不是“,”今天就放了一个错,用错了符号。
test(map);
}