POST和GET结果whit jQuery和php错误

时间:2016-02-12 18:52:58

标签: php jquery

我想从这种方式发送获取数据并创建输入,这个jquery 并发布到PHP页面并获得结果 但问题是:

  

警告:为

中的foreach()提供的参数无效

的jQuery

$('#ss').live('click', function () {
    $("#main_login").html("<center>waiting plaese . . . .</center>");
    var arr = $("#myInputs").val();
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: "myInputs=" + arr,
        success: function (data) {
            $('#main_login').html(data)
        }

    });
});


$(function () {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;


    $('#text').live('click', function () {
        $('<p><input type="text" id="myInputs" size="20" name="myInputs[]" value="" placeholder="Input Value" /> <a href="#" id="rtext">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });
});

HTML

<a href="#" id="text">add</a><br>

<div id="p_scents">
    <p><label for="p_scnts"><input type="text" id="myInputs[]" size="20" name="myInputs[]" value="" placeholder="Input Value" /></label></p>
<div id="main_login"></div>

PHP

$name = $_POST['myInputs'];
foreach( $name as $key => $n ) {
    print "The name is ".$n." and email is , thank you<br>";
}

1 个答案:

答案 0 :(得分:1)

The issue is with your javascript, not the PHP. These lines:

<tr ng-repeat="product in products | filter:search | orderBy:'name'">
        <td>{{product.name}}</td>
        <td>{{product.category}}</td>
    </tr>

Problems

  1. Because you're using a CSS ID selector you're only allowed one element with that ID
  2. var arr = $("#myInputs").val(); [...] data: "myInputs=" + arr, will only return the value of the first element, and it will be a string, not an array
  3. $("#myInputs").val() will send the POST data as a string, not an array

Solutions

You need to do a couple things to fix these issues:

  1. Switch "myInputs=" + arr to use a CSS class (i.e. id='myInputs[]')
  2. Pull all values from the class='myInputs' elements and combine them in an array (hint: use jQuery's .each function)
  3. Change .myInputs to array format (i.e. "myInputs=")

Let me show you:

HTML

{ "myInputs[]" : arr }

Javascript

    <p><label for="p_scnts"><input type="text" class="myInputs" size="20" name="myInputs[]" value="" placeholder="Input Value" /></label></p>