使用 AJAX 提交 html 表单并显示来自外部 api 的 json 响应

submit html form with AJAX and display json response from external api

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

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

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

调试控制台中的警告:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.ssllabs.com/api/v2/analyze?&host=www.domain.com. This can be fixed by moving the resource to the same domain or enabling 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 + "");
      },

    });
  });

});

跨源请求被阻止:意味着您不能从 http:// 调用 https:// 站点,大多数浏览器都禁用此功能。

解决方案:

1) 对数据类型使用 jsonp 而不是 json: "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. 现在 ajax 从您的 javascript 而非 https://api.ssllabs.com/api/v2/analyze?

    呼叫 api.php
    $.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+ "");

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

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

编辑:此请求成功规避了 Cross-Origin 策略,但仍会导致 Unexpected Token : 错误。有关 CORS headers 的更多信息,请参阅 here for more information on this error. If you have access to the server from which you're requesting data, add the response header Access-Control-Allow-Origin:'*'. See here