简体   繁体   English

如何通过AJAX发送PHP数组?

[英]How to send a PHP array via AJAX?

On my signup page people can sign up for my website by filling in some inputs ad checkboxes. 在我的注册页面上,人们可以通过填写一些输入广告复选框来注册我的网站。 It's basically a form that sends the data to a PHP page with ajax which then puts it in the database. 它基本上是一个将数据发送到带有ajax的PHP页面的表单,然后将其放入数据库中。

The javascript gets the values from the form like this for example 例如,javascript从表单中获取值

var w = _("website").value;
var bio = _("bio").value;

and then sends it like this ajax.send("w="+w+"&bio="+bio); 然后像这样发送ajax.send("w="+w+"&bio="+bio); This is working as it should, but I want to add something. 这是应该的,但我想添加一些东西。

Now I have a number of checkboxes that I want to get in an array that gets posted in one variable via ajax. 现在我有一些复选框,我希望在一个数组中通过ajax发布在一个变量中。 So in my form I have this piece of PHP: 所以在我的表单中我有这段PHP:

$licensessql = mysqli_query($db_conx, "SELECT * FROM licenses");
while($licenserecord = mysqli_fetch_assoc($licensessql)) {
echo '<input type="checkbox" value="'.$licenserecord["license"].'" name="licenses[]" id="'.$licenserecord["license"].'"><label for="'.$licenserecord["license"].'">'.$licenserecord["license"].'</label><br>';
}

Using pure PHP this would work and put all the values from the checkboxes in an array licences[], but I have no idea how to achieve this using ajax. 使用纯PHP,这将工作,并将复选框中的所有值放在数组license []中,但我不知道如何使用ajax实现此目的。 If I have 5 checkboxes, I want the javascript var to have for example the value 'value1,value2,value3' and have that posted to PHP. 如果我有5个复选框,我希望javascript var具有例如值'value1,value2,value3'并将其发布到PHP。

Thanks! 谢谢!

First of all I recommend using form serialization as posted in other answers. 首先,我建议使用其他答案中发布的表单序列化。

To answer your actual question: "If I have 5 checkboxes, I want the javascript var to have for example the value 'value1,value2,value3' and have that posted to PHP." 要回答你的实际问题: "If I have 5 checkboxes, I want the javascript var to have for example the value 'value1,value2,value3' and have that posted to PHP."

Here's a fully working example (using 3 checkboxes) which will produce a javascript variable which you can use to pass to your AJAX post method for PHP to process. 这是一个完整的工作示例(使用3个复选框),它将生成一个javascript变量,您可以使用该变量传递给您的AJAX post方法以供PHP处理。

JSFiddle: https://jsfiddle.net/o5q04vf0/ JSFiddle: https ://jsfiddle.net/o5q04vf0/

Code Snippet: 代码片段:

 $(document).ready(function() { $('#btnTest').click(function() { var checkBoxValues = $("[name=licenses\\\\[\\\\]]").map(function() { if ($(this).is(':checked')) { return this.value; } }).get().join(); alert(checkBoxValues); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" value="0" name="licenses[]" /> <input type="checkbox" value="1" name="licenses[]" /> <input type="checkbox" value="2" name="licenses[]" /> <button id="btnTest">Submit</button> 

This will help you guide in the right direction but do consider switching your approach in passing data through AJAX like other members suggested here. 这将帮助您指导正确的方向,但请考虑通过AJAX传递数据,就像这里建议的其他成员一样。

Use POST and serialize the array as data 使用POST并将数组序列化为数据

  $data = $('form').serialize(); $.post( "ajax/test.html", function($data) { $( ".result" ).html( data ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="demo_form.asp"> <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br> <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br> <input type="submit" value="Submit"> </form> 

in PHP you use $_POST['attributeName'] to read the value 在PHP中,您使用$_POST['attributeName']来读取值

You can send all form data with serializeArray function. 您可以使用serializeArray函数发送所有表单数据。
Serialize use for GET, and serializeArray is useful for POST. Serialize用于GET, serializeArray对POST很有用。

$('#btn-send').click(function(e) {
    $.ajax({
        url: 'url-to-data-send',
        method: 'post',
        data: $(this).closest('form').serializeArray(); <--- send form data
    }).done(function(response) {
        alert('form sent');
    })
});

or you can specify what you want to send definetely 或者您可以指定要发送的内容

var data = $(this).closest('form').serializeArray();
    console.log(data);

FIDDLE 小提琴

** EDIT ** **编辑**

This does what you want I guess 这就是你想要的

var arr = [];
$.map( $(this).closest('form').find('input[name="chck[]"]:checked'), function( n, i ) {
     arr.push({ name: $(n).attr('name'), value: $(n).val()});
});
console.log(arr);

FIDDLE 2 FIDDLE 2

Here we go: 开始了:

You need Serialize function! 你需要Serialize功能! Here is an exaple how you may use it: 以下是您如何使用它的一个问题:

HTML: HTML:

<form id="yourOrderFormId" method="post">
<input type="checkbox"/><input type="text"/>
<input type="checkbox"/><input type="text"/>
<button id="yourButtonId">Send</button>
</form>

jQuery Ajax: jQuery Ajax:

<script>
    $('#yourButtonId').click(function(e) {

       var yourData = $("#yourOrderFormId").serialize(); 

        $.ajax({
            method: 'POST',
            url: '/yourUrl',
            data: yourData,
            dataType: 'html',
           success:success: function (result) {
           alert("Your message sent!");
           }
    });

Or use with serializeArray(); 或者与serializeArray()一起使用;

console.log($('form').serializeArray());

Here : enter link description here 在这里:在此输入链接描述

Hope it helps;) 希望能帮助到你;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM