ThisClark ThisClark - 1 year ago 61
Javascript Question

ajax error results in success function call

I was working toward a solution for this recent post: Repeating a function using array of values and in doing so, I stitched together the following piece of code.



<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>

var name_list = ['mike','steve','sean','roger'];

var successAction = function(name) {
console.log(name);
}

name_list.forEach(function(name) {
jQuery.ajax({
type: "GET",
url: "https://www.google.com/",
dataType: 'html',
success: successAction(name)
});
});

</script>





I run this and not surprisingly the following error message is returned:


Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).




My question is this - If the ajax request results in four failures such as it appears, then why is the success function called four times and correspondingly logging each name in the array?

Answer Source
success: successAction(name) 

could be replaced with

xxx: successAction(name)

and it would still print out the 4 times. The correct syntax should be

success: function(name) { successAction(name); }