简体   繁体   English

使用AJAX查询将javascript数组传递给php

[英]using AJAX query to pass javascript array to php

After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working. 在阅读完这里的很多文章之后(甚至只是直接复制代码),我仍然无法弄清楚为什么它不起作用。

On my main page, I have a textbox that a user pastes data into. 在我的主页上,我有一个文本框供用户粘贴数据。 Upon paste, this script runs (this and the ajax query below are in the same script function): 粘贴后,此脚本将运行(以下命令下面的ajax查询在同一脚本函数中):

var lines = $('textarea').val().split('\n');  //create array from pasted data

I now have a JavaScript array with the pasted data. 我现在有一个带有粘贴数据的JavaScript数组。 I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following: 我正尝试将其发送到一个单独的PHP文件,该文件将通过执行以下操作加载到此主页上的div中:

$.ajax({
      type: 'POST',
      url: 'return.php',
      data: {lines:lines},        
        success:function(data){
          $("#info").load("return.php");
        }
  });

  for (i=0; i < lines.length; i++) {            // log the output
    if (lines[i]){
    console.log("line ",  i , lines[i]);
    }  
  }

In my return.php file, I have this: 在我的return.php文件中,我有这个:

$lines = $_REQUEST['lines'];

echo '<pre>';
echo($lines);
echo '</pre>';

My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank. 我的console.log可以完美地输出数组,但是由于某些原因,它没有进入return.php,因为我的回声是空白。

What am I doing wrong? 我究竟做错了什么?

The response I get from return.php is: 我从return.php得到的响应是:

 <pre>testArrayArray
(
    [0] => DL4004-13-F
    [1] => S1G-13-F
    [2] => ZXMP3A13FTA
    [3] => B260A-13-F
    [4] => S1J-13-F
    [5] => S3B-13-F
    [6] => SSN1N45BTA
    [7] => GBJ1010-F
    [8] => BPW20RF
    [9] => T3035H-6I
    [10] => ZXMP7A17KTC
    [11] => 
)
</pre>

The success handler on your ajax request is calling return.php with nothing and loading it into #info. 您的ajax请求的成功处理程序将不执行任何操作调用return.php并将其加载到#info中。

Change success to instead do: 将成功更改为:

$("#info").html(data)

The $lines variable in your PHP code is an array, not a string. PHP代码中的$lines变量是一个数组,而不是字符串。 If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code). 如果您打开了错误,PHP应该警告您您正在执行“数组到字符串的转换”(至少使用您的代码对我有用)。

You can't echo an array like that, you have to iterate through the results somehow. 您不能echo的数组,而必须以某种方式遍历结果。

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

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