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 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加