【发布时间】:2013-04-06 16:28:44
【问题描述】:
拿起了 knockout.js,我正在尝试使用 PHP(更具体地说是 Laravel 框架)将数据保存到 mysql 数据库中。这是ajax:
$.ajax("save", {
data: ko.toJSON(this), // turns the input into JSON I assume?
type: "post",
success: function() {
alert("Success!"); // right now I'm alerting the data to troubleshoot
}
});
以及我将数据保存到数据库中的方法:
// I expect my ajax to send me data that is in json format
// I then decode the data to get an array which I can use to run my query
$data = json_decode(Input::json(), true);
return DB::table('content')->insert($data);
但是,问题是我似乎正在接收对象类型的数据(在$data 上运行gettype() 并且json_decode() 也返回了错误),准确地说是stdClass Object。在对我的 javascript 中发生的事情进行故障排除后,我提醒了数据,它是 JSON 格式,所以它必须工作。
我确实让它像这样工作:
$data = json_encode(Input::json(), true);
return DB::table('content')->insert(json_decode($data), true);
这很成功,保存到数据库等。但是我很困惑。请原谅我对 JSON 的缺乏经验,但过程不应该是:
- 在前端将数据编码为 JSON
- 向服务器发送数据
- 在后端解码数据,将其转换为服务器可以处理的格式(本例中为数组)
- 插入数据
所以,在我的第一次尝试中,$data = Input::json() 是对象类型。 Json_decode 抛出一个错误,因为它需要一个字符串,现在我有点迷路了,因为我需要 JSON。
【问题讨论】:
-
我不知道
Laravel但我认为您需要将 JSONcontentType设置添加到您的 ajax 调用中。所以试试$.ajax("save", { data: ko.toJSON(this), // turns the input into JSON I assume? contentType: "application/json", type: "post", success: function() { alert("Success!"); // right now I'm alerting the data to troubleshoot } }); -
@nemesv 试过了,不走运。仍在接收对象。
-
@ejx 也许
Input::json()已经解码了json字符串?否则只需var_dump()it,这样您就可以检查它包含的内容。
标签: javascript knockout.js laravel json