admin管理员组

文章数量:1332359

$("select#product-id").change(function(){
    $("input#product-name").val("Loading...");
    var value = $(this).val();
    $.ajax({
        url: "http://localhost/api/purchase-entry-data.php",
        data: {
            product_id : value
        },
        type: "POST",
        success: function(data){
            $("input#product-name").val(data);
        },
        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.

$("select#product-id").change(function(){
    $("input#product-name").val("Loading...");
    var value = $(this).val();
    $.ajax({
        url: "http://localhost/api/purchase-entry-data.php",
        data: {
            product_id : value
        },
        type: "POST",
        success: function(data){
            $("input#product-name").val(data);
        },
        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.

Share Improve this question edited Nov 23, 2019 at 14:15 Hello World asked Feb 9, 2017 at 19:51 Hello WorldHello World 2,9077 gold badges31 silver badges66 bronze badges 3
  • What do you mean by 2 values in ajax result? – void Commented Feb 9, 2017 at 19:52
  • What does the data look like when it is returned from your AJAX? – WillardSolutions Commented Feb 9, 2017 at 19:52
  • It is something like this var product = {desc:"Android ", size:"5.5"} Thanks – Hello World Commented Feb 10, 2017 at 18:31
Add a ment  | 

1 Answer 1

Reset to default 6

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);

本文标签: javascriptHow to split ajax resultStack Overflow