简体   繁体   English

使用jQuery .load()从输入到PHP加载数组?

[英]Load array from inputs to PHP with jQuery .load()?

Ok, I've been looking and looking for about 2 weeks now and I've yet to find exactly what I need to figure out, so now is the time to ask the experts! 好的,我一直在寻找和寻找约两周的时间,我还没有找到我需要弄清楚的东西,所以现在是时候向专家们询问了!

I'm working on an advertising management system and one of the parts of the request form is to select start and end dates for an ad. 我正在制作广告管理系统,请求表单的其中一个部分是选择广告的开始和结束日期。 The user is given an option of adding more dates. 用户可以选择添加更多日期。

So, there are two inputs that are there initally... 所以,最初有两个输入......

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

Then, under that is an option to dynamically add more inputs. 然后,在此下面是动态添加更多输入的选项。 When the user adds more inputs, it just copies those initial inputs, so we end up with more instances. 当用户添加更多输入时,它只是复制那些初始输入,因此我们最终会有更多实例。 For example: 例如:

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">

Is there a way to send the results of these inputs as an array using .load()? 有没有办法使用.load()将这些输入的结果作为数组发送? I have it sending and displaying the info for one set of inputs with the code below... 我有它发送和显示一组输入的信息与下面的代码...

var startDate = $("#startDateInput").val();
var endDate = $("#endDateInput").val(); 
$("#adBooking").show().load('../scripts/checkSpots.php', { startDate: startDate, endDate: endDate});

I guess I just don't 100% understand how to do this. 我想我不是100%了解如何做到这一点。 I've been racking my brain for the past two weeks but I can't find anything totally relevant to what I'm doing. 过去两周我一直在绞尽脑汁,但我找不到与我正在做的事情完全相关的事情。

But, what I need to do is make an array of data out of all the startDate and endDate inputs and then throw it through the .load() and into the checkSpots.php page and have it display the information for each set of start/end dates. 但是,我需要做的是从所有startDate和endDate输入中生成一个数据数组,然后通过.load()并将其抛入checkSpots.php页面并让它显示每组start /的信息结束日期。

Is there a different way of doing this? 有没有不同的方式这样做? Maybe a more efficient way? 也许是一种更有效的方式? Or, if anyone can shed a bit of light on this broken jQuery noob, I'd greatly apprecaite it! 或者,如果有人能够对这个破碎的jQuery noob有所了解,我会非常感激它! :D :d

$(function() {
    $("#add-date").click(function(e) {
        var i = $('.end-date').length + 1;
        $('<p class="dates">' + 
          '<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' + 
          '<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' + 
          '</p>').insertAfter('.dates:last');
          e.preventDefault();
    });
    $('#my-form').submit(function() {
        var post_data = $(this).serialize();
        //$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
        alert(post_data);
        return false;
    });

PHP PHP

<?php
   foreach($_POST['startDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 07/12/2011
    }
   foreach($_POST['endDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 09/12/2011
    }
?>

First things first, ID's need to be unique, so when a new date pair is added, append a qualifier on the end of the id: 首先,ID需要是唯一的,所以当添加新的日期对时,在id的末尾附加一个限定符:

<input type="text" name="startDate[]" id="startDateInput1">
<input type="text" name="enddate[]" id="endDateInput1">

<input type="text" name="startDate[]" id="startDateInput2">
<input type="text" name="enddate[]" id="endDateInput2">

Or better yet, use a class: 或者更好的是,使用一个类:

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

Then you can apply some jQuery voodoo whenever you'd like (button click, submit, etc): 然后你可以随时应用一些jQuery voodoo(按钮点击,提交等):

$('#myButton').click(function(){

    // Our ajax post data. For example, $_POST['startDates'][2] would 
    // give you the 3rd start date in your php file.
    var data = {
        startDates: new Array(),
        endDates: new Array()
    };

    // Loop through each date pair, extract its value, and add it to our post data
    $('.startDateInput').each(function(){
        data.startDates.push(this.val());
    });
    $('.endDateInput').each(function(){
        data.endDates.push(this.val());
    });

    // Load it!
    $('#result').load('doSomething.php', data);

});

Note: Above code is not tested, just an example of one possible solution. 注意:以上代码未经过测试,只是一个可能解决方案的示例。

Hope that helps. 希望有所帮助。 Oh, and obligatory Family Guy reference . 哦,和强制性的家庭盖伊参考

I bumped int this problem lately, and I found aSeptik solution is very useful. 我最近碰到了这个问题,我发现一个智能解决方案非常有用。

But there is a mistake in it. 但它有一个错误。 From jQuery documentation : jQuery文档

Request Method 请求方法

The POST method is used if data is provided as an object; 如果数据作为对象提供,则使用POST方法; otherwise, GET is assumed. 否则,假设GET。

Since the result of the .serialze() function is string the .load() methode will use GET. 由于.serialze()函数的结果是字符串,因此.load()方法将使用GET。

JS code (same): JS代码(相同):

$(function() {
    $("#add-date").click(function(e) {
        var i = $('.end-date').length + 1;
        $('<p class="dates">' + 
          '<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' + 
          '<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' + 
          '</p>').insertAfter('.dates:last');
          e.preventDefault();
    });
    $('#my-form').submit(function() {
        var post_data = $(this).serialize();
        //$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
        alert(post_data);
        return false;
    });

PHP script with _GET: 带有_GET的PHP脚本:

<?php
   foreach($_GET['startDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 07/12/2011
    }
   foreach($_GET['endDate'] as $key => $val ) {
         echo $key;  // 1
         echo $val; // 09/12/2011
    }
?>

There is a major flaw in your logic: Any id attribute must be unique in the document. 您的逻辑存在一个主要缺陷:任何id属性在文档中必须是唯一的。 As you use several id's more than once, it will not work or give unexpected results at best. 由于您不止一次使用多个ID,它将无法工作或充其量地产生意外结果。

First, you shouldn't use the same id on multiple elements within a single html page. 首先,您不应在单个html页面中的多个元素上使用相同的id。 That's going to cause all sorts of unpredictable behavior. 这将导致各种不可预测的行为。 Use class instead so: 使用类代替:

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">

Then you need to query for all the input elements using jquery loop through each element and assign its value to the appropriate array. 然后,您需要使用jquery循环查询所有输入元素,并将其值分配给相应的数组。

var myEndDateArray = [], myStartDateArray = [];
$(".endDateInput").each(function() {
     myEndDateArray.push($(this).val())

});
$(".startDateInput").each(function() {
     myStartDateArray.push($(this).val())

});

Finally, you must post the array data to your page in a compatible post format. 最后,您必须以兼容的帖子格式将数组数据发布到您的页面。

$("#adBooking").show().load('../scripts/checkSpots.php', { 'startdate[]': myStartDateArray, 'enddate[]': myEndDateArray});

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

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