PHP将变量和数组post到Jquery
我有两个字段:PHP将变量和数组post到Jquery,php,jquery,ajax,arrays,post,Php,Jquery,Ajax,Arrays,Post,我有两个字段: <input type="text" name="smsText" value="text sms to send to all"> <input type="text" name="recipients[]" value="3471234567"> <input type="text" name="recipients[]" value="3359876543"> <input type="text" name="recipients[
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
请,我需要帮助修改我的函数,通过Ajax将“smsText”和数组收件人[]发送到其他php页面
多谢各位 查看jQuerys函数。serializeArray()和.serialize()替换以下代码:
var recipients = $("input[name=recipients]").val();
var datastr ='text=' + text +'&recipients=' + recipients;
对于这一个:
var datastr = '';
$("input[name='recipients[]']").each(function() {
datastr += '&recipients[]=' + $(this).val();
});
datastr ='text=' + text + datastr;
这将满足您的需要,并使PHP创建数组变量$\u POST['recipients']
,其中包含您的所有值。尝试:
var datastr = '&recipients[]=';
var arr = [];
$("input[name='recipients[]']").each(function() {
arr[] = $(this).val();
});
datastr ='text=' + text + datastr + arr;
如果字段包含在表单中,则可以使用jQuery的serialize()方法将字段转换为字符串,以便通过Ajax发送
<form id="sms-form">
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
</form>
$("#sendSms").click(function(){
var datastr = $("form#sms-form").serialize();
$(over).appendTo('#box');
$.ajax({
type: "POST",
url: "send-result.php",
data: datastr,
cache: false,
success: function(data){
$('#box').html(data);
}
});
return false;
});
$(“#发送SMS”)。单击(函数(){
var datastr=$(“表单#sms表单”).serialize();
$(结束)。附加到(“#框”);
$.ajax({
类型:“POST”,
url:“send result.php”,
数据:datastr,
cache:false,
成功:功能(数据){
$('#box').html(数据);
}
});
返回false;
});
试试看
html
<form name='ohForm' action="#">
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
// and others components
</form>
php
print_r($_POST['data']);
此行
datastr+='&recipients[]='+$(This.val()
会将&recipients[]=
连接几次,这不是必需的。@coder1984您错了,如果您想让PHP为所有收件人[]
值创建一个数组变量,这是必需的。@Nelson:太棒了!这就成功了!非常感谢您和所有其他人!您好,如果您想使用'post'方法,您必须形成参数列表,如数据:{name:“John”,location:“Boston”}
…希望它能帮助您<代码>$.ajax({type:“POST”,url:“some.php”,数据:{name:“John”,location:“Boston”}).done(函数(msg){alert(“保存的数据:+msg);})代码>参见示例您的代码无效javascript错误:第10行出现问题字符7:应为标识符,而应为“]”。arr[]=$(this.val()代码>
$("#sendSms").click(function(){
var form = $("form[name='ohForm']");
var datastr = form.serialize();
$(over).appendTo('#box');
$.ajax({
type: "POST",
url: "send-result.php",
data: datastr,
cache: false,
success: function(data){
$('#box').html(data);
}
});
return false;
});
print_r($_POST['data']);