简体   繁体   English

未执行 JQuery 获取请求回调函数

[英]JQuery get request callback function not being executed

My code is relatively simple.我的代码比较简单。 I have a URL, which is defined before the request is sent, I then have a $.get() request, which I expect to return back a JSON object.我有一个在发送请求之前定义的 URL,然后我有一个$.get()请求,我希望它返回一个 JSON 对象。 The code is below.代码如下。

var url = "url"; //Removed for clarity

$.get(url, function (data) {
        alert("hi");
});

The url being used within the request is correct.请求中使用的 url 是正确的。 I have copied and pasted the code into my browser and I receive the response that I expect from the endpoint.我已将代码复制并粘贴到我的浏览器中,并收到了我期望从端点发出的响应。

However when this JQuery code is executed, the callback function is not called and the alert is not fired.但是,当执行此 JQuery 代码时,不会调用回调函数,也不会触发警报。 Why is this happening?为什么会这样?

Edit: Forgot to post the error message I found in the console.编辑:忘记发布我在控制台中发现的错误消息。

I'm receiving this:我收到这个:

2Initial%20Loan#:1 Access to XMLHttpRequest at 
'-snip url-' from 
origin 'https://localhost:44358' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the requested resource.

Will it have anything to do with the GET request not working?它与 GET 请求不起作用有什么关系吗?

There might be some problem with the url.网址可能有问题。 The syntax specified by you is correct and the same is checked您指定的语法是正确的,并检查相同

var url = "https://jsfiddle.net/"; //Removed for clarity

$.get(url, function (data) {
    alert("hi");
});

working code工作代码

This is a classic example of CORS, which stands for Cross origin resource sharing.这是CORS的经典例子,代表跨源资源共享。 Browsers prevent sending AJAX request to domain other than where the javascript file originated from.浏览器会阻止将 AJAX 请求发送到 javascript 文件来源之外的域。

As the error message says you have to set 'Access-Control-Allow-Origin' http response header from your server code.正如错误消息所说,您必须从服务器代码设置“Access-Control-Allow-Origin”http 响应标头。 Read more about CORS here [enter link description here CORS MDN在此处阅读有关 CORS 的更多信息 [在此处输入链接描述CORS MDN

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

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