简体   繁体   English

jQuery上的API调用

[英]API call over jQuery

I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. 我正在尝试建立一个.js文件,该文件将数据发送到外部API,等待响应并解释结果。 The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). 外部API是基于XML的,并且接受以XML为正文(内容类型; text / xml)的HTTPS Post。 I can call the API correctly via cURL. 我可以通过cURL正确调用API。

This is what I have so far: 这是我到目前为止的内容:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">

<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';

function CallService() {
   $.ajax({
      url: webServiceURL, 
      type: "POST",
      dataType: "xml", 
      data: xmlString, 
      processData: false,
      contentType: "text/xml; charset=\"utf-8\"",
      success: OnSuccess, 
      error: OnError
});
  return false;
}

function OnSuccess(data, status) {
  alert(data.d);
}

function OnError(request, status, error) {
  alert('error');
}

$(document).ready(function() {
  jQuery.support.cors = true;
});
</script>
</body>
</html>

When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). 当我打开HTML时,我收到一条警告,提示“错误”,并且另一端(外部API)未显示任何内容。 Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call? 有没有一种方法可以仅使用JavaScript / Ajax / jQuery来执行此操作,或者我是否需要接收JS调用的“支持”代码?

When you want to make cross domain queries, you have basically 3 types of solution : 当您想进行跨域查询时,基本上有3种解决方案:

1) use JSONP , which won't interest you if you're using XML and not JSON 1)使用JSONP ,如果您使用的是XML而不是JSON,则不会引起您的兴趣

2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page 2)通过在服务主要html页面的服务器上设置一种代理(或任何类型的get),实际上并不是跨域

3) changing headers on the server to specify to the browser that you accept cross-domain queries. 3)更改服务器上的标头以向浏览器指定您接受跨域查询。 This is new but yet accepted by all major browsers. 这是新功能,但所有主要浏览器都接受。 That's called CORS . 那就是CORS It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins). 在所有服务器端语言中更改标头(“ Access-control -...”)都很容易,因此现在应该成为跨语言的首选方式(如果您遇到问题(安全性,权限,带宽,广告等) -域访问您提供的数据,则可以限制允许的来源)。

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

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