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?
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With