如何等待ajax请求并处理结果? [英] How can I wait for an ajax request and process the result?

查看:93
本文介绍了如何等待ajax请求并处理结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开一个网站,然后等待所有重定向完成.然后,我捕获一个验证码图像,并通过nodejs将其发送给用户.然后我输入键入的验证码:

I open a website, then wait for all redirects to be done. Then I capture a captcha image, and send it via nodejs to a user. Then I recive the typed captcha:

    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();

    await page.goto('http://localhost/p1.php' );
    await page.waitForNavigation();

    const captcha_image = await page.$eval('#security', e => e.getAttribute('src'));

    io.emit('send_captcha_to_client' , {text : captcha_image });

    var captcha = await captchaPromise;

收到capthca的键入值后,将其放在字段中,然后单击登录按钮:

After I receive the typed value of the capthca, I put it in the field and click the login button:

    await page.$eval('#W_CAPTCHA', (el , _captcha) => el.value = _captcha.W_CAPTCHA , captcha );

    await page.click('#login-btn');

现在,单击按钮后,Ajax请求将发送到服务器.可以说 http://example.com/login.php -如果验证码正确,我将重定向到我的仪表板,但是如果ajax调用返回,则说 {status:er}

Now after clicking the button, an ajax request will be sent to the server. Lets say http://example.com/login.php - if the captcha is right, I will get redirected to my dashboard, but if the ajax call returns lets say {status:er}

在页面中有< span id ="alert"></span> ,它将向其中添加 .Error 类并放入那里的错误文本.如何拦截ajax调用并检查登录是否成功?

And there is <span id="alert"></span> in the page it'll add .Error class to it and put the error text in there. How can I intercept the ajax call and check if the login was successful or not?

我可以检查ajax调用的结果,或者等待并检查文档中的 div.Error .但是我不确定我该怎么做.这是我失败的尝试:

I can check the result of the ajax call or wait and check the document for div.Error. But I am not sure how can I do any of them. Here is my failed attempt:

await page.waitForNavigation();

page.waitForSelector('.Error');
const error  = await page.$eval('.Error', e => e.value );

console.log(error);

browser.close();

推荐答案

您可以同时等待,并处理最先发生的情况:

You can wait on both simultaneously and handle whichever occurs first:

await Promise.race([
  page.waitForNavigation({ waitUntil: "networkidle0" }),
  page.waitForSelector(".Error")
]);

if (await page.$(".Error")) {
  // there was an error
} else {
  // the page changed
}

这篇关于如何等待ajax请求并处理结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆