$ .getJSON没有从PHP中提取JSON

时间:2017-07-10 05:13:53

标签: javascript php jquery json

我正在尝试使用此PHP代码创建我创建的JSON:

if ($result=mysqli_query($conn,$sql))
{
   $rowcount=mysqli_num_rows($result);
}

$myJSON = json_encode($rowcount);

echo $myJSON;

我正在尝试将值$ myJSON添加到Javascript变量中。目前,我的代码如下所示:

var maxqty; 
$.getJSON('[URL in here or .php file]', data, function(jsonData) {
maxqty = jsonData; 
}); 

我知道这应该是一件非常简单的事情,但我无法理解我的代码出错的地方。我认为我的PHP文件输出的格式不正确或我的$.getJSON调用错误。当我将$ .getJSON调用说

时出错
  

未捕获的引用错误:未定义数据。

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

只需在代码中传递header('Content-Type: application/json');

<?php
    if ($result=mysqli_query($conn,$sql))
    {
       $rowcount=mysqli_num_rows($result);
    }
    header('Content-Type: application/json');
    echo json_encode($rowcount);

也在您的脚本中

var maxqty; 
$.getJSON('http://localhost/karthi/test.php', function(jsonData) {
maxqty = jsonData; 
console.log(jsonData);
});

如果将任何值传递给服务器,请为数据分配值

data = 'list'; 
 var maxqty; 
    $.getJSON('http://localhost/karthi/test.php', data, function(jsonData) {
    maxqty = jsonData; 
    console.log(jsonData);
    });

答案 1 :(得分:2)

首先,您需要在PHP代码中添加标头。 标题(&#39;内容类型:application / json&#39;);

然后问题在于jquery,你的代码不知道数据变量是什么

$。getJSON(&#39; [此处的网址或.php文件]&#39;,数据,功能(jsonData)

数据是将发送到服务器的参数,可以是任何平面文本,也可以不是。只需在传递数据之前为数据分配任何东西

答案 2 :(得分:1)

从服务器加载东西需要时间。从回调内部设置外部变量将无法按预期工作。

// The request start here
var request = $.getJSON('[URL in here or .php file]', data);

var maxqty = undefined;

request.done(function (data) {
    // This callback is called when the data is done
    // loading. The "data" variable is only available
    // here, and not outside the callback

    maxqty = data;
});

// "maxqty" is "undefined" here until the request
// is done loading
console.log(maxqty);