weixin_33709590 2018-07-23 06:19 采纳率: 0%
浏览 28

使用json的Ajax响应

so i am sending some query to a php page using java script ajax using data type json. but when the value returning from the php page as json_encode() method i cant show it on the requested page. here is my code:

    var wishlist = {
    'add': function(product_id) {
    // alert(product_id);
    $.ajax({
        url: 'includes/wishlist.php',
        type: 'post',
        data: 'product_id=' + product_id +'&type=add',
        dataType: 'json',
        success: function(response) {
            alert(response);
            var x = JSON.parse(response);
            alert(x);
       });
   },

and here is my php page code

$pid= $_POST['product_id'];
$type = $_POST['type'];
$sql = "select * from category where id = '".$pid."'";
$exe = mysql_query($sql);
while($result = mysql_fetch_assoc($exe)){
    $value = json_encode($result);
 }
echo $value;

thanks in advance.

  • 写回答

1条回答 默认 最新

  • 妄徒之命 2018-07-23 12:57
    关注

    A few issues:

    1)

    while($result = mysql_fetch_assoc($exe)){
        $value = json_encode($result);
     }
    echo $value;
    

    Unless it so happens that your query only returns one row, this code will give you a problem - every time your while loop runs, you'll overwrite $value with a totally new value, so you'll only ever see the last line of data returned by your query.

    If you know the query will only ever return one row, then the while can be replaced with if:

    if($result = mysql_fetch_assoc($exe)){
        $value = json_encode($result);
     }
    echo $value;
    

    But if you might return multiple rows, you need to change it to:

    $values = array();
    while($result = mysql_fetch_assoc($exe)){
        $values[] = $result;
     }
    echo json_encode($values);
    

    so that you get a single JSON array containing all the results.

    2) var x = JSON.parse(response); - due to dataType: "json", response is already an object. By setting the dataType option as "json" you told jQuery to automatically parse it for you. So you don't need to parse it yourself, therefore this line is redundant.

    Doing alert(response); probably gets you something meaningless like [object] shown in the alert, since response is an object, and you can't just display an object as text. You can either stringify it to display the whole object, or pick a specific property to display and alert that, e.g.

    Show the whole object:

    alert(JSON.stringify(response));
    

    Show a particular attribute:

    alert(response.id);
    

    3) This isn't broken in this case, but I recommend not building your data string yourself. It means you don't get the benefit of proper URI-encoding of your data, which jQuery can take care of for you. This means that if you send any characters in your data which have special meaning in a querystring (e.g. & or ?, for example), your string will break and the server won't understand what you've sent it. You won't notice if you're just sending a simple integer or something, but you should get into the habit of doing this so you encounter problems in future.

    Instead, give jQuery an object containing the data, and it'll take care of building the querystring for you and encoding it correctly:

    data: { "product_id" : product_id, "type": "add" },
    

    4) This is not directly related to your issue, but it's nonetheless a serious thing which you need to sort out urgently: Why are you using the long-deprecated mysql_ code library? It was discontinued many years ago and removed entirely in PHP7. No new code should be written using this library. It leaves you vulnerable to SQL injection attacks (due to the lack of parameterised query support) and potentially other unpatched vulnerabilities. Switch to using mysqli or PDO as soon as possible, and then learn how to write parameterised queries to protect your data from malicious input. See http://bobby-tables.com for a simple explanation of the risks and some sample PHP code to write queries safely.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀