简体   繁体   中英

Can't get the result from a PHP script with jQuery

I'am trying to call a PHP script on my local server with jQuery inside an CasperJS function, but somehow I don't get the result. Here is my code:

casper.then(function() {
    var result = casper.evaluate(function() {
        var result = $.get('http://localhost/test.php', function() {});
        return result;
    });
    result = JSON.stringify(result);
    this.echo(result);
    this.exit();
});

It does not matter which URL is called, it delivers always the same result:

{"abort":{},"always":{},"complete":{},"done":{},"error":null,"fail":{},"getAllRe
sponseHeaders":{},"getResponseHeader":{},"overrideMimeType":{},"pipe":null,"prog
ress":{},"promise":{},"readyState":1,"setRequestHeader":{},"state":{},"statusCod
e":{},"success":null,"then":{}}

Things I have checked:

  • XAMP server is running and working
  • PHP file is there
  • Any other URL also does not work and delivers the result (see above)
  • Also the jQuery function $.load() does not work (the result is then "null")
  • jQuery is loaded correctly (otherwise CasperJS throws an error)
  • If I simply return it works correctly (eg return "test"; )

Don't know what to do. Thanks for any suggestions!

$.get is asynchronous, its result won't be available until the callback is called.

casper.then(function() {
    var _this = this;
    casper.evaluate(function() {
        $.get('http://localhost/test.php', function(result) {
            _this.echo(result);
            _this.exit();
        });
    });
});

I would recommend changing your async to false in $.ajaxSetup();

and also, you should get your return data from within the callback success function

casper.then(function() {
    var result = casper.evaluate(function() {

        var $return = ''; // initiate $return

        var async = $.ajaxSetup()['async'];
        $.ajaxSetup({'async':false}); // Set async to false

        $.get('http://localhost/test.php', function( data ) {

            $return = data; // test.php return data is saved to $return

        });

        $.ajaxSetup({'async': async }); // Set async to back to original value

    });
    result = JSON.stringify($return);
    this.echo(result);
    this.exit();
});

The only downside to this, thanks to Esailija for pointing it out, is that your page will 'hang' until the request is completed

Nowhere on the jQuery docs for $.get() does $.get() return the contents of the page. You're using the http transport instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM