我如何发布一个数组并使用PHP循环它?

时间:2017-07-10 19:19:47

标签: javascript php jquery mysql arrays

我有一个输入字段,当用户输入内容时,它会立即使用jQuery replace函数创建一个数组。目标是将这些值发送到PHP并在MySQL中的特定表上执行实时搜索。

我得到了input字段和ajax调用的一部分,但到目前为止我还没有完成php循环的部分。

我的目标是将此数组序列化为php并将每个项目用作变量。

这是我的jQuery和HTML fiddle

这是我的代码:

HTML:

<div class="container-fluid" style="margin-top:10px;">
  <div class="row" style="padding:10px;">
    <input class="form-control" id="Input">
  </div>
  <div class="row">
    <div class="container rounded" id="smd" style="background-color:red; height:100px;display:none;">
<span>Search Results here</span>
    </div>
  </div>
</div>

jQuery的:

 $("#Input").keyup(function() {
  var div = $('#smd');
  if ($("#Input").val().length > 0) {
    div.show();
    var source = $("#Input").val();
    var splittedSource = source.replace(/\s{2,}/g, ' ').split(' ');
    $.post('/url/to/page', splittedSource);

    console.log(splittedSource);
  } else {
    div.hide();
  }
});

这就是我的字符串的样子:

["This", "is", "my", "string"]

0:"This"
1:"is"
2:"my"
3:"string"

3 个答案:

答案 0 :(得分:0)

您需要作为键/值对发送,或者发送和接收为application/json

现在您只发送一个没有可由$_POST

索引的密钥的值

尝试

$.post('/url/to/page',{arr: splittedSource});

在php中

$arr = $_POST['arr'];//php array

以json:

来做
$.ajax({
   url: '/url/to/page',
   contentType:'application/json',
   data: JSON.stringify(splittedSource)
   // other options
});
//php
$arr = json_decode(file_get_contents('php://input'),true);

答案 1 :(得分:0)

虽然我觉得您可以(甚至应该)在后端代码中处理此类逻辑,但您可能需要查看how to use arrays in a form上的手册

这表明您应该使用以[]结尾的名称。由于在默认情况下发布表单只是使用application/x-www-form-urlencoded enctype,您只需将值myarray[]=a&myarray[]=b ...等放在请求正文中,PHP就会将其解释为数组值$_POST['myarray']

答案 2 :(得分:0)

这是常见的格式

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

您需要发送正确的格式,如

$.post( "test.php", { name: "John", time: "2pm" } );

因此您的代码需要更新

$.post('/url/to/page', splittedSource); 

$.post('/url/to/page',{data: splittedSource});

所以你可以使用

获取数据
<?php
$data = $_POST['data'];

您也可以使用此格式

$("button").click(function(){
    $.post("demo_test_post.asp",
    {
        name: "Donald Duck",
        city: "Duckburg"
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

有关ajax帖子的更多信息

https://api.jquery.com/jquery.post/

相关问题