PhantomJs - Getting value out of page.evaluate + ajax (Synchronous Version)

不羁的心 提交于 2019-12-06 09:27:56

问题


Problem: Extracting data from ajax request inside page.evaluate

Description: I usually get variables out of page.evaluate by simply returning them. However, I need to make an ajax request within the context of a page, and then I need to process its result out of the page's context.

The code I'm trying to fix is:

var theOutput = page.evaluate(function () {
    return $.ajax({
        async: false,
        url: 'http://localhost:8080/captcha.php',
        data: { filename: 'C:\\wamp\\www\\images\\0.png' },
        type: 'post',
        success: function (output) {
            parsed_output = $.parseHTML(output);
            return parsed_output[4].data.trim();
        },
    });
});
console.log(theOutput);

The variable parsed_output[4].data.trim() is a string. But when I log output I get a [object Object], with the properties abort, always, complete, done, error, fail, getAllResponseHeaders, getResponseHeader, overrideMimeType, pipe null, progress, promise, readyState, setRequestHeader, state, statusCode, success,then.

Question: How can I extract theOutput from page.evaluate?


回答1:


Since this is a blocking AJAX request, you can create a temporary variable:

var theOutput = page.evaluate(function () {
    var result;
    $.ajax({
        async: false,
        ...
        success: function (output) {
            parsed_output = $.parseHTML(output);
            result = parsed_output[4].data.trim();
        },
    });
    return result;
});
console.log(theOutput);

You can also directly access the responseText from the jqXHR object:

var theOutput = page.evaluate(function () {
    var jqXHR = $.ajax({
        async: false,
        url: 'http://localhost:8080/captcha.php',
        data: { filename: 'C:\\wamp\\www\\images\\0.png' },
        type: 'post'
    });
    parsed_output = $.parseHTML(jqXHR.responseText);
    return parsed_output[4].data.trim();
});
console.log(theOutput);

If you fear that async: false is deprecated, you can simply use the underlying XMLHttpRequest to use blocking execution:

var theOutput = page.evaluate(function () {
    var request = new XMLHttpRequest();
    request.open('POST', 'http://localhost:8080/captcha.php', false);
    request.send($.param({ filename: 'C:\\wamp\\www\\images\\0.png' }));

    var parsed_output = $.parseHTML(request.responseText);
    return parsed_output[4].data.trim();
});
console.log(theOutput);


来源:https://stackoverflow.com/questions/28705536/phantomjs-getting-value-out-of-page-evaluate-ajax-synchronous-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!