带有ajax xml请求的节点js脚本无法正常工作

时间:2016-04-14 03:32:08

标签: javascript jquery ajax xml node.js

我有一个简短的javascript脚本,我在节点上运行(例如node runScript.js)。在其中,我使用tiptoe,并且我尝试了各种方法来检索xml文件但没有成功。



tiptoe(
 	function getESData() {
 		var json;
                // get the json data.
	        for (var i = 0; i < json.hits.hits.length; i++) {	        	
	        	for (var multiId = 0; multiId < json.hits.hits[i]._source.multiverseids.length; multiId++) {
	        		var priceUrl = "http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s="+setName+"&p="+json.hits.hits[i]._source.name
					console.log("fetching " +priceUrl );
                  
                    // attempt 1:
					var x = new XMLHttpRequest();
					console.log("working"); // THIS CONSOLE LOG NEVER SHOWS UP.
					x.open("GET", priceUrl, true);
					console.log("working");
					x.onreadystatechange = function() {
						if (x.readyState == 4 && x.status == 200)
						{
							console.log(x.responseXML);
						}
					};
					x.send();
                  
                    // attempt 2:
					$.ajax({
						url: priceUrl,
						success: function( data ) {
						  console.log(data);
						}
					});
                  
                    // attempt 3:                  
					$.get(priceUrl, function(data, status){
				        console.log("Data: " + data + "\nStatus: " + status);
				    });
				}
			}
	    });
 	}
);
&#13;
&#13;
&#13;

所有这些方法都默默地失败了(显然我在测试时注释了除了一个,我不会同时使用所有三个),打印完第一个console.log后我记录了url以确保它有效。 (带有变量的URL解析为这样的:http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=Ice Age&p=Arnjlot's Ascent当我在浏览器中测试它时绝对返回xml,所以我知道它正在工作)。这是脚尖的东西吗?

编辑:尝试4:

&#13;
&#13;
    $().ready(function () {
      console.log('working');
	  $.get(priceUrl, function (data) {
	    console.log(data);
	  });
	});
&#13;
&#13;
&#13;

在“工作”之前,这也失败了。日志显示在我的控制台中。不确定这是否重要,但我也在使用git bash控制台。

编辑2:答案是以下列方式使用request

&#13;
&#13;
request(priceUrl, function(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
})
&#13;
&#13;
&#13;

完美无缺。

1 个答案:

答案 0 :(得分:1)

又一个Access-Control-Allow-Origin问题。我尝试了你给的链接:

  

XMLHttpRequest无法加载http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=Ice%20Age&p=Arnjlot%27s%20Ascent。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点'null'访问。

有关可能的解决方案的文档post here

在您的情况下,您可以使用jsonp数据类型作为您的请求,这仅适用于jQuery 1.12 / 2.2 +

var url = "http://partner.tcgplayer.com/x3/phl.asmx/p?pk=TCGTEST&s=Ice Age&p=Arnjlot's Ascent";

$.get({
    url: url,
    dataType: 'jsonp text xml'
}, function(data, status) {
    console.log("Data: " + data + "\nStatus: " + status);
});
相关问题