【发布时间】: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 或者我的代码中是否还有其他错误?