doulv8162 2017-02-09 19:51
浏览 26
已采纳

如何拆分ajax结果

$("select#product-id").change(function(){
    $("input#product-name").val("Loading...");
    var value = $(this).val();
    console.log(value);
    $.ajax({
        url: "http://localhost/a/ac/submits/purchase-entry-data.php",
        data: {
            product_id : value
        },
        type: "POST",
        success: function(data){
            $("input#product-name").val(data);
            //$("input#product-name").val(data.productDesc);
            //$("input#product-name").val(data.productSize);
        },
        error: function (){
            $("input#product-name").val("No Data Available");
        }
    });
});

I am tring to use ajax result in two places (there is two value in the ajax result 1. Product Name, 2. Product Size).
So how to split up that that result in two different values in php.

  • 写回答

1条回答 默认 最新

  • duandu5846 2017-02-09 20:01
    关注

    This depends how you are returning the data back to ajax. There are several ways you can do this.

    Using split

    In your purchase-entry-data.php file you could return data with a separator then use split to get both values. Just make sure you use a separator that will not be contained in the data returned. Here I used a pipe

    echo "productDesc|productSize";
    

    Then in jquery you can split it up and access each element in the array

    var result= $(data).text().split('|');
    var productDesc = result[0];
    var productSize = result[1];
    

    Using JSON

    In your php file return the data in an array and JSON

    <?php
    $arr = array('productDesc' => 'Description', 'productSize' => 'Size');
    echo json_encode($arr);
    ?>
    

    Then in jquery access it like

    data = $.parseJSON(data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接