【问题标题】:submit html form with AJAX and display json response from external api使用 AJAX 提交 html 表单并显示来自外部 api 的 json 响应
【发布时间】:2015-06-10 10:39:26
【问题描述】:

我有一个非常基本的表单,只有一个输入字段。我想使用 AJAX 提交此表单并在页面上的 div 中显示响应。

一些要点。 - 来自 API 的响应是 JSON 数据类型。 - API 与发出请求的客户端不在同一台服务器上。

使用我当前的代码,我可以看到正在发出请求,但我没有得到任何回报。我确实在调试控制台中看到了警告,但我不确定如何继续或如何更新我的代码以使其正常工作。

调试控制台中的警告:

跨域请求被阻止:同源策略不允许读取 远程资源在 https://api.ssllabs.com/api/v2/analyze?&host=www.domain.com。这个可以 通过将资源移动到同一域或启用 CORS 来修复。

-- 我的 HTML --

<body>
  <form id="myAjaxRequestForm">
    <fieldset>
      <legend>Request</legend>
      <p>
        <label for="hostname">Host:</label>
        <input id="hostName" type="text" name="hostName" />
      </p>
      <p>
        <input id="myButton" type="button" value="Submit" />
      </p>
    </fieldset>
  </form>
  <div id="anotherSection">
    <fieldset>
      <legend>Response</legend>
      <div id="ajaxResponse"></div>
    </fieldset>
  </div>
</body>

-- 我的 Jquery 与 AJAX--

$(document).ready(function() {

  //Stops the submit request
  $("#myAjaxRequestForm").submit(function(e) {
    e.preventDefault();
  });

  //checks for the button click event
  $("#myButton").click(function(e) {

    //get the form data and then serialize that
    dataString = $("#myAjaxRequestForm").serialize();

    //get the form data using another method
    var hostName = $("input#hostName").val();
    dataString = "host=" + hostName;

    //make the AJAX request, dataType is set to json
    //meaning we are expecting JSON data in response from the server
    $.ajax({
      type: "GET",
      url: "https://api.ssllabs.com/api/v2/analyze?",
      data: dataString,
      dataType: "json",

      //if received a response from the server
      success: function(response) {
        $("#ajaxResponse").append("<b>Server Name:</b> " + response.first + "");
        $("#ajaxResponse").append("<b>Port:</b> " + response.second + "");
        $("#ajaxResponse").append("<b>Protocol:</b> " + response.third + "");
      },

    });
  });

});

【问题讨论】:

  • 我将数据类型更新为“jsonp”,重新运行 api 调用并在调试控制台中收到此错误 SyntaxError: missing ; before 语句 analyze:1:7 文件“analyze”属于 api 服务器 - 这是否意味着它不支持 jsonp 或者我的代码中是否还有其他错误?

标签: jquery html ajax cors


【解决方案1】:

Cross-Origin Request Blocked:意味着您不能从 http:// 调用 https:// 站点,并且大多数浏览器都禁用此功能。

解决方案:

1) 使用 jsonp 而不是 json 作为 dataType: "json" 如果可行,一切都很好

2) 如果不支持jsonp,在你的工作目录下创建一个php文件,通过curl访问API。并以 json 形式回显响应。然后只从你的ajax调用那个php。

如果 JSON 失败则更新

我假设你使用的是 php

  1. 在您的目录中创建一个名为 api.php 的 php 文件

    <?php
    header( "Content-Type: application/json" );
    //create cURL connection
    $curl_connection =curl_init('https://api.ssllabs.com/api/v2/analyze?host='.$_REQUEST['host']);
    
    ///set options
    curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
    
    
    //perform our request
    $result = curl_exec($curl_connection);
    echo $result;
    //close the connection
    curl_close($curl_connection);
    
    
    ?>
    
  2. 现在从您的 javascript 而非 https://api.ssllabs.com/api/v2/analyze 对 api.php 进行 ajax 调用?

    $.ajax({
      type: "GET",
      url: "yourhost/yourpath/api.php", //change this that suits you
      data: dataString,
      dataType: "json",
      ....
    

最后填充这样的值

    $("#ajaxResponse").append("<b>Server Name:</b> " + response.endpoints[0].serverName+ "");
    $("#ajaxResponse").append("<b>Port:</b> " + response.port+ "");
    $("#ajaxResponse").append("<b>Protocol:</b> " + response.protocol+ "");

【讨论】:

  • 感谢您的建议。我尝试了您的第一个解决方案。我将数据类型更新为“jsonp”,重新运行 api 调用,并在调试控制台中收到此错误 SyntaxError: missing ; before 语句 analyze:1:7 文件“analyze”属于 api 服务器 - 这是否意味着它不支持 jsonp 或者我的代码中是否还有其他错误?
  • 请添加以下行,让我看看你的输出。控制台.log(结果);在成功函数的第一行
  • 当然,我做到了。我在哪里可以找到 console.log 输出?
  • F12 for chrome 并单击控制台选项卡
  • 它来自 chrome:analyze?&callback=jQuery111003550140524748713_1428300933030&host=www.verisign.com&_=1428300933031:1 Uncaught SyntaxError: Unexpected token :
【解决方案2】:

由于您使用的是 JSON,您可以将 dataType 属性更改为 jsonp,请求将成功完成,忽略跨域策略。

$.ajax({
  type: "GET",
  url: "https://api.ssllabs.com/api/v2/analyze?",
  data: dataString,
  dataType: "jsonp",
...

编辑:此请求成功绕过跨域策略,但仍会导致Unexpected Token : 错误。有关此错误的更多信息,请参阅here。如果您有权访问从中请求数据的服务器,请添加响应标头Access-Control-Allow-Origin:'*'。有关 CORS 标头的更多信息,请参阅 here

【讨论】:

  • 我将数据类型更新为“jsonp”,重新运行 api 调用,CORS 警告消失了,但现在我在调试控制台中收到此错误 SyntaxError: missing ; before 语句 analyze:1:7 文件“analyze”属于 api 服务器 - 这是否意味着它不支持 jsonp 或者我的代码中是否还有其他错误?
  • 不幸的是,这似乎是服务器不支持 JSONP 的结果。我通过查看this post 确定了这一点,因此它可能是一个开始寻找答案的好地方。此外,This slideshow 是了解跨域政策的绝佳信息来源。
猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 2018-02-05
  • 2011-12-17
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
相关资源
最近更新 更多