ajax错误导致成功函数调用

时间:2021-02-16 20:27:46

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

跨源请求已阻止:同源策略禁止在https://www.google.com/上阅读远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin')。


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?

我的问题是 - 如果ajax请求导致出现四次失败,那么为什么成功函数被调用四次并相应地记录数组中的每个名字?

1 个解决方案

#1


2  

success: successAction(name) 

could be replaced with

可以替换为

xxx: successAction(name)

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

它仍会打印出4次。应该是正确的语法

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

#1


2  

success: successAction(name) 

could be replaced with

可以替换为

xxx: successAction(name)

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

它仍会打印出4次。应该是正确的语法

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