我正在进行一些 AJAX ColdFusion 测试,在使用 AJAX 将数据发送到 ColdFusion 服务器时遇到问题。 这是我的 HTML 代码:
<form method="post">
<p>
<input type="text" id="user_name" name="name" placeholder="name" value="test" />
<input type="text" id="user_email" name="email" placeholder="email" value="abc" />
</p>
<input type="button" value="Find Out" class="ajax_form"/>
</form>
<p id="insert"></p>
JS:
$(document).ready(function (){
$(".ajax_form").click(function (){
var that = $(this).parent(),
url = "ajax.cfc",
type = that.attr('method'),
test = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
test[name] = value;
});
console.log(test.name);
$.ajax({
url: url,
type: type,
data: {
method: "testCheck",
name: test.name,
email: test.email,
array: test
},
success: function (responce){
document.getElementById('insert').innerHTML = responce;
},
error: function (xhr, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
ajax.cfm 非常简单,如下所示。
<cfcomponent output="false">
<cffunction name="testCheck" access="remote" returnformat="plain" returnType="string" output="false">
<cfargument name="name" type="string" required="false" />
<cfargument name="email" type="string" required="false" />
<cfargument name="array" required="false" />
<cfset var string = " " />
<cfif (arguments.name) eq "test">
<cfset string = arguments.array/>
<cfelse>
<cfset string = "incorrect" />
</cfif>
<cfreturn string />
</cffunction>
</cfcomponent>
问题是 cf 参数未定义(我得到的错误:“500(元素数组在参数中未定义)”)或在设置它时获取默认值。我猜测这与我发送的对象的数据类型有关,但我无法提出任何解决方案。在这种情况下是否可以使用这种类型的数据作为参数?
最佳答案
该错误主要是由于以下原因造成的:
数组
作为对象(JSON):
您将 array
作为对象发送,因此将使用 contentType
为 application/x-www-form-urlencoded
发出请求通过 jQuery(因为您没有明确指定它)。
因此,对象(本例中的array
)将被序列化为名称/值对,并将附加到 URL 中,因此服务器将获得以下参数(这不是我们想要的):
数组[名称] = '测试'
数组[电子邮件] = 'abc'
因此,您必须从客户端序列化数据,然后在服务器端反序列化,如下所示:
$.ajax({
url: url,
type: type,
data: {
method: "testCheck",
name: test.name,
email: test.email,
array: JSON.stringify(test) <--- Serialize here -->
}
, success: function (responce){
document.getElementById('insert').innerHTML = responce;
}
, error: function (xhr, textStatus, errorThrown){
alert(errorThrown);
}
});
<--- Deserialize --->
<cfset local.array = deserializeJSON(arguments.array)>
- 参数数组没有默认值
参数array
没有默认值,并且在请求期间未传递(由于上述原因),因此,它将是未定义
。
关于javascript - ColdFusion AJAX : Element is undefined in arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678596/