简体   繁体   English

使用json_encode将数据从php传递到javascript问题

[英]passing data from php to javascript problems with json_encode

I am kinda lost as to why I cant get data passed 我有点迷茫,为什么我无法通过数据
javascript JavaScript的

jQuery.extend({
getValues: function(url) {
    var result = null;
    $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    async: false,
    success: function(data) {

        result = JSON.stringify(data);

    }
return result;

I have no problems with the js part the problem is the php 我的js部分没有问题,问题是php

$sql = "SELECT name, score FROM scores ORDER BY score DESC LIMIT 10 ";
$result = mysqli_query($conn1, $sql);
if (mysqli_num_rows($result) > 0) {
$data = array(); 
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = array("name"=>$row['name'], "score"=>$row['score']);
    $post_data = json_encode(array($data));
}
echo $post_data;
}

echoing post data gives nothing if i echo post data inside while loop i get a result for every iteration of while loop. 如果我在while循环内回显帖子数据,则回显发布数据将无济于事。while循环的每次迭代都会得到结果。 If i print_r data array i also get some kind of result. 如果我print_r数据数组,我也会得到某种结果。 My question is what am i doing wrong? 我的问题是我做错了什么?
Thank you for your answers I did bring out post data from the loop that was poorly made indeed however the real problem was that one of the names was in russian alphabet and the result from database wasnt utf-8 谢谢您的回答,我确实从循环中提取出的数据确实做得不好,但真正的问题是名称之一是俄语字母,而数据库的结果不是utf-8

Write $post_data = json_encode(array($data)); $post_data = json_encode(array($data)); after your while loop, otherwise you will be overwriting $post_data on each iteration. 在while循环之后,否则每次迭代都会覆盖$post_data

while ($row = mysqli_fetch_assoc($result)) {
    $data[] = array("name"=>$row['name'], "score"=>$row['score']);
}
$post_data = json_encode(array($data));
echo $post_data;

I don't expect this to solve your core problem, but you did ask "what am I doing wrong". 我不希望这能解决您的核心问题,但是您确实问过“我在做什么错”。

Let us know what you get with var_export($data); 让我们知道您使用var_export($data);会得到什么var_export($data); after the loop and before the json_encode() . 在循环之后和json_encode()之前。 We need to see what that data & structure looks like. 我们需要查看数据和结构的外观。

Change 更改

result = JSON.stringify(data);

For: 对于:

result = JSON.parse(data);

使用json_last_error我发现我无法编码,因为数据不是utf-8

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

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