如何将drp.getDateRange
的输出转换为数组,以便我可以通过AJAX发布?
我已更新此代码以表示以下建议
<script>
var drp;
var myArray = [];
function makedatepicker() {
drp = $("#myDate").datepicker({});
}
function getRange() {
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
data: data,
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
}
});
}
$(document).ready(function () {
makedatepicker();
});
</script>
答案 0 :(得分:2)
关于JSON的注释。默认编码将是url表单编码。如果您希望请求以JSON格式发送数据,则需要添加..
content-type: "application/json; charset=utf-8",
如果你要返回JSON,你应该添加......
datatype : "json",
不确定您在后端使用哪种脚本语言,但如果使用PHP,则可以发回这样的数组数据
echo json_encode($myArray);
我将把JSON内容添加到下面的示例代码中。
结束更新
如果您使用.serialize(),则将其作为ajax数据发送,它将显示在您的帖子或获取数组中。
如果您正在使用数组,则可能需要使用.serializeArray()
在开发者工具(Chrome或FF中的F12)中查看对象或数组var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
beforeSend : function (){
console.log("Before Send: Data looks like..");
console.dir(data);
},
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
console.log("parsing JSON ...");
console.dir($.parseJSON(response));
}
});
Chrome开发者工具控制台,您可以在此处看到console.log或console.dir
的任何内容
您可以点击“网络”标签查看正在发送的JSON。然后单击ajax脚本的名称,它将显示正在发送的数据。 (另外,单击“响应”选项卡将显示脚本发回的内容。)
在下面的示例中,我使用上面的代码发送一个ajax请求,它显示数据确实是一个JSON对象。