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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘