开发者

how to send values from PHP to jQuery: echo or return?

开发者 https://www.devze.com 2023-01-11 01:18 出处:网络
I just wanted to check something here - do you have to echo values in PHP to retrieve them via (jQuery)XHR?

I just wanted to check something here - do you have to echo values in PHP to retrieve them via (jQuery)XHR?

for example

PHP:

public function processRequest() {

    //intercept AJAX requests
    if (!empty($_GET)) {

        if (isset($_GET['xhr'])) {
            if ($_GET['xhr'] == true) {
                //process AJAX

                //call relevant method
                echo json_encode(array('key' => 'value'));
                return;
            }
        }
    }

    //else proceed with regular output
    $this->render();
}

jQuery:

function doAjax(){

    $.ajax({
        url: "index.php?xhr=true",
        cache: false,
  开发者_开发问答       dataType: 'json',
         success: function(data){
             console.log(data);
         }
    });
}

This logs a json object in Firebug console with the appropriate values. If I try and return the value instead of echoing, I get nada.


They have to be echoed to be in the response, so yes they have to be there for jQuery to see them...otherwise the response that the browser gets won't have the content.

As a side note, you can check for the X-Requested-With: XmlHttpRequest header if all you want is to check if it's an AJAX request from jQuery, it already adds this header with every request, for example:

if($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){


Return won't do anything because you're not in a function, you're in a separate file. Return will just stop execution gracefully.

You need to echo / print the data for javascript to read it when doing its http request. It does the same as if you'd take that url and open it in your browser.


The response will consist of the rendered page, so when you return it, it returns it within the PHP file, the actual render of the page never sees the value, and therefore neither does jQuery.

Essentially, the jQuery AJAX command will see what your browser will see if you view source.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号