简体   繁体   English

使用ajax将php数组传递给javascript

[英]pass php array to javascript using ajax

I try to get array from sql server using php , and parsing these array to javascript using ajax. 我尝试使用php从sql服务器获取数组,并使用ajax将这些数组解析为javascript。 However , I have tried many solution by google , I can't get the array. 但是,我已经尝试了谷歌的许多解决方案,我无法获得数组。

This is my php code: 这是我的PHP代码:

<?php
    include 'Connect.php';
    $Store_int = $_GET['num'];

    $sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;

    mysqli_select_db($link, "web");
    $link->set_charset("utf8");
    $result = mysqli_query($link, $sql);

    $arr = array();
    while ($row = mysqli_fetch_object($result)) {
        $p = (string)$row->Name;
        $arr[] = $p;
    }
    //print_r($arr);
    $jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
    echo $jsonArr;
    mysqli_free_result($result);
    mysqli_close($link);
?>

Array in php will encode and display: PHP中的数组将编码并显示:

["pen","pencil","apple","cat","dog"]

and the .js file 和.js文件

function getArr(store_int) {
    var jsArray = new Array();
    $.ajax({
        url: "fromSQL_store.php",
        data: {
            num: $("#store_int").val()
        },
        type: "GET",
        dataType: "json",
        success: function (data) {
            alert(num);
            jsArray = JSON.parse(data.jsonArr);
        }, error: function (data) {
            alert("123");
        }
    });
    //alert(jsArray.length);
    return jsArray;
}

In .js , I will always get empty response(undefined) from php. 在.js中,我将始终从php得到空响应(未定义)。 Because the ajax will answer "error" function..., and the error status is 200. 因为ajax将回答“错误”功能...,并且错误状态为200。

Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. 由于AJAX调用是异步的,因此数组将始终返回undfined ,函数将在设置之前返回jsArray and You don't need JSON.parse() as you have defined dataType as json in your ajax call. 并且您不需要JSON.parse()因为您已经在ajax调用中将dataType定义为json Pass a function to your getArr() function and use your data in that function. 将函数传递给getArr()函数,然后在该函数中使用数据。

function getArr(store_int, outputFn){ // what do you use store_int for?
   $.ajax({
       url: "fromSQL_store.php",
       data: {
           num: $("#store_int").val()
       },
       type: "GET",
       dataType: "json",
       success: function(data) {
           outputFn(data)
       },error: function(data){
           alert("123");
       }
   });
}

Then use it like 然后像

getArr('5', function (data) {
       console.log(data)
})

Console output 控制台输出

在此处输入图片说明

Your problem lies here. 您的问题就在这里。 You are attempting to access data.jsonArr which is always undefined. 您正在尝试访问始终未定义的data.jsonArr The JSON data sent is actually embodied by data variable. 发送的JSON数据实际上是由data变量体现的。

success: function(data) {
    alert(num);
    jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}

NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. 注意,您可能还需要指定要输出的MIME媒体类型为JSON。 Putting this at the top of your PHP script should solve your problem. 将其放在您的PHP脚本的顶部应该可以解决您的问题。

<?php
header('Content-Type: application/json');

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

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