简体   繁体   中英

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. 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. 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. 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?

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. Browsers prevent sending AJAX request to domain other than where the javascript file originated from.

As the error message says you have to set 'Access-Control-Allow-Origin' http response header from your server code. Read more about CORS here [enter link description here CORS MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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