如何将变量转换为json? [英] How to convert variables into json?
问题描述
我想将json数据发送到ajax,但是如何将变量转换为json或将数组转换为json?
I want to send json data to ajax but how do you convert variables into json or convert an array to json?
$(".confirm_order").click(function(event) {
event.preventDefault();
var street = $("#street").val();
var location = $("#location").val();
var number = $("#number").val();
var f = ???
$.ajax({
type: 'post',
url: "/orders",
dataType: "json",
data: f,
success: function (l) {
alert("Done");
}
});
});
推荐答案
如果你真的想将数据转换为JSON,你必须创建一个对象或数组并使用 JSON.stringify
(在较新的浏览器中可用,并且可以从这里):
If you really want to convert the data into JSON, you have to create an object or array and use JSON.stringify
(available in newer browser and can be loaded form here):
var f = JSON.stringify({street: street, location: location, number: number});
但你不能只设置数据
属性到 f
然后。您必须将其分配给另一个变量:
but you cannot just set the data
attribute to f
then. You have to assign it to another variable:
data: {data: f}
这将产生如下的POST参数:
This will produce the POST parameters like so:
data={"number":"value of number","location:...}
但是,没有理由在这里创建JSON。我会将这些值作为普通的post参数发送。为此您只需创建一个上面的对象并将其分配给 data
:
However, there is not reason to create JSON here. I would sent the values as normal post parameters. For that you just create an object like above and assign it to data
:
data: {street: street, location: location, number: number}
这将创建POST参数:
This will create the POST parameters:
street=valueofstreet&location=valueoflocation&...
这将更容易,因为您不必解析服务器端的JSON。
This would be easier as you don't have to parse the JSON at the server side.
这篇关于如何将变量转换为json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!