multiple return values from PHP with jQuery AJAX

前端 未结 3 608
刺人心
刺人心 2020-12-23 02:34

I\'m using this jQuery code:

$.ajax
({
    type: \"POST\",
    url: \"customerfilter.php\",
    data: dataString,
    cache: false,
    success: function(htm         


        
相关标签:
3条回答
  • 2020-12-23 03:01

    Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.

    Example:

    <?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?>
    

    In Javascript:

    $.getJSON("myscript.php", function(data) {
      alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
    });
    
    0 讨论(0)
  • 2020-12-23 03:05

    Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:

    $.ajax
    ({
        type: "POST",
        url: "customerfilter.php",
        dataType: 'json',
        cache: false,
        success: function(data)
        {
            $(".custName").html(data.message1);
            $(".custName2").html(data.message2);
        }
    });
    

    Then you need to encode your response as a JSON Array:

     <?php echo json_encode(
          array("message1" => "Hi", 
          "message2" => "Something else")
     ) ?>
    
    0 讨论(0)
  • 2020-12-23 03:08

    Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.

    0 讨论(0)
提交回复
热议问题