简体   繁体   English

没有浏览器,是否可以进行ajax调用?

[英]Are ajax calls possible without a browser?

I'm trying to create JavaScript tests using mocha and chutzpah, this means all my tests are done browserless. 我正在尝试使用mocha和chutzpah创建JavaScript测试,这意味着我所有的测试都是在无浏览器的情况下完成的。 The issue I'm running into is that all my AJAX calls are returning an empty string, even the following does not work: 我遇到的问题是我所有的AJAX调用都返回一个空字符串,即使以下情况也不起作用:

$.ajax({
    url: "http://www.something.com/",
    //Ajax events
    async: false,
}).done(function(data) {
    test = data;
});

Here, the test is set to '', I've tried many different combinations of AJAX parameters too such as the async , type , dataType , success , etc. 在这里,测试设置为”,我也尝试了AJAX参数的许多不同组合,例如asynctypedataTypesuccess等。

So my question is, are AJAX calls possible without a browser? 所以我的问题是,没有浏览器就可以进行AJAX调用吗?

I took a quick look at chutzpah and it seems that it's implemented on top of Phantom.js. 我快速浏览了chutzpah,看来它是在Phantom.js之上实现的。 So you're not running your test without a browser. 因此,没有浏览器就无法运行测试。 On the contrary, you're running your test inside a Webkit based browser - albeit one without a GUI. 相反,您正在基于Webkit的浏览器中运行测试-尽管没有GUI。

Since your test is running inside a browser, all browser restrictions apply. 由于您的测试在浏览器中运行,因此所有浏览器限制都适用。 This includes the same-origin-policy. 这包括同源策略。 So depending on how chutzpah loads your test script your ajax call may fail. 因此,根据chutzpah加载测试脚本的方式,ajax调用可能会失败。

If chutzpah loads your test page from disk then same-origin-policy always fails. 如果chutzpah从磁盘加载测试页,则same-origin-policy总是失败。 I don't know much about chutzpah but if it's possible make it load your test page from a URL (you can always run a test server on localhost). 我对chutzpah不太了解,但是如果可以的话,可以从URL加载测试页(您始终可以在localhost上运行测试服务器)。

You can actually disable security features in Phantom.js by passing --web-security=false on the command line. 您实际上可以通过在命令行上传递--web-security=false来禁用Phantom.js中的安全功能。 Not sure how you'd do that from Mocha and chutzpah but that is another option you can investigate. 不知道如何从Mocha和chutzpah中做到这一点,但这是您可以研究的另一种选择。

So my issue was stupid. 所以我的问题很愚蠢。 Ajax queries on top of the framework I was using needed the "www." 我正在使用的框架顶部的Ajax查询需要“ www”。 So instead of doing a call to "google.com" I needed to do a call to "www.google.com". 因此,我不需要拨打“ google.com”,而是需要拨打“ www.google.com”。 The www redirection wasn't working. www重定向无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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