简体   繁体   中英

Accept JSON from backbone.js Sync in PHP

I am implementing Backbone.js, and I am just trying to understand how the sync function works. To keep it very simple, here is the model.

var Item = Backbone.Model.extend({

defaults: {
  name: "Goo"
},

url: "commlink.php"
});

and then

Backbone.sync("create", item);

This is my commlink.php

$item=json_decode($_POST);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");

I see a new row show up in my DB, however, the field "name" is blank. I tried both item.save() and the above method...both ended up with the same blank cell but a new entry.

This is the error in chrome in network/content:

<b>Warning</b>:  json_decode() expects parameter 1 to be string, array given in ...XXX...

This is in the request payload:

{"name":"Goo"}
$rawJSONString = file_get_contents('php://input');
$item = json_decode($wrapperString);
//$item->name is the data you want
$item = json_decode(file_get_contents('php://input'), true);
print_R($item);

Found this is more helpful

https://coderwall.com/p/vwvy_a

SECURITY NOTE: as pointed out in the comment this is not the way you should ACTUALLY insert the user provided content into your database, this is simply to show you how to get access to the array information as JSON, you should use prepared statements, a framework database adapter, or some other appropriate solution for escaping the user provided content before sticking it into the database.

You're trying to run an array ($_POST) through a function (json_decode) that only accepts a string. The solution in this specific example would be to do this:

$results=$mdb2->query("INSERT INTO list VALUES (NULL, '{$_POST['name']}')");

This would work because you're accessing $_POST as the associative array that it is.

However what I think you actually want to do is first convert the $_POST array to json, then decode it so you can use it the way you wanted to (accessing it as an object, which the json_decode returns):

$item=json_encode($_POST);
$item=json_decode($item);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");

For reference:

http://php.net/manual/en/function.json-decode.php

http://php.net/manual/en/function.json-encode.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM