Get variable from PHP file using JQuery/AJAX

前端 未结 1 639
一整个雨季
一整个雨季 2020-12-01 07:11

This is my first post here and I hope that someone will be able to help me. For the past week I have been working on a project of mine. Apparently, I have stuck with the las

相关标签:
1条回答
  • 2020-12-01 07:31

    If I understand right, you need to use JSON. Here is a sample.

    In your PHP write:

    <?php
    // filename: myAjaxFile.php
    // some PHP
        $advert = array(
            'ajax' => 'Hello world!',
            'advert' => $row['adverts'],
         );
        echo json_encode($advert);
    ?>
    

    Then, if you are using jQuery, just write:

        $.ajax({
            url : 'myAjaxFile.php',
            type : 'POST',
            data : data,
            dataType : 'json',
            success : function (result) {
               alert(result['ajax']); // "Hello world!" alerted
               console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
            },
            error : function () {
               alert("error");
            }
        })
    

    And that's all. This is JSON - it's used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. :)

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