我想将数组作为数据发送,但是我收到错误的请求错误!
我该如何解决? 是否需要添加任何其他代码?
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
dataString = [ 'Location Zero', 'Location One', 'Location Two' ];
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "test",
data: {
data: jsonString
},
cache: false,
success: function() {
alert("OK");
},
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
答案 0 :(得分:1)
我的第一直觉告诉我你的AJAX方法中的URL格式不正确..是“测试”一个带有index.php文件的目录吗?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "test", // Should this be test.php or /test or ../test or somethign?
data: {
data: jsonString
},
cache: false,
success: function() {
alert("OK");
},
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
答案 1 :(得分:1)
如果@silversunhunter的答案没有锻炼,请尝试以这种方式对阵列进行字符串化。按原样发送。代码
dataString = [ 'Location Zero', 'Location One', 'Location Two' ];
$.ajax({
type: "POST",
url: "test", // Should this be test.php or /test or ../test or somethign?
data: JSON.stringify({ 'data': dataString }),
cache: false,
success: function() {
alert("OK");
},
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
还要确保您的webmethod期望一个string []类型的参数,并命名为' data'
答案 2 :(得分:0)
应添加以下行:
dataString = [ 'Location Zero', 'Location One', 'Location Two' ];
var ourObj = {};
ourObj.data = dataString;
和ajax数据更改为:
data: {"points" : JSON.stringify(ourObj)},
此链接很有帮助! http://www.coderslexicon.com/easy-way-to-post-multiple-javascript-values-to-php-using-jquery-ajax/