当前位置: 代码迷 >> JavaScript >> Sencha touch 与PHP 如何进行json 数据解析
  详细解决方案

Sencha touch 与PHP 如何进行json 数据解析

热度:644   发布时间:2012-12-16 12:02:32.0
Sencha touch 与PHP 怎么进行json 数据解析

ST 可以把数据包装成json格式发送到php端

cartItemsStore = Ext.getStore('cartitemsconvert');
				var allData = [];
				cartItemsStore.each(function(records){
					allData.push(records.getData());
				});
				var dataToBeSentToServer = Ext.JSON.encode(allData);
				console.log(dataToBeSentToServer);

然后用jsonp或是ajax将数据传输到PHP端

Ext.data.JsonP.request({
            		url: 'http://londit-50c03e41547f8.com.1130.url-test.com/dingcan/php/save-orders.php',
            		callbackKey: 'callback',
            		params: {
		                sendData:dataToBeSentToServer
            		},
            		timeout:2000,
            		success: function(result, request) {
	                	console.log('提交数据成功');
	            	}
        		});

然后PHP怎么获得这些json数据呢?红色部分是php的问题。如果不用stripslashes转换。stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。否则数据打印出来是空,还有个解决办法就是:The fix was to turn off magic_quotes in php.ini. If you do this, you will no longer need the call to stripslashes(). 

$sendData = $_REQUEST['sendData'];
$jsondata = stripslashes($sendData);
//$sendData = '[{"id":"1","food":"\u5f20\u96ea\u6885","age":"27","subject":"\u8ba1\u7b97\u673a\u79d1\u5b66\u4e0e\u6280\u672f"},{"id":"2","food":"\u5f20\u6c9b\u9716","age":"21","subject":"\u8f6f\u4ef6\u5de5\u7a0b"}]';
$arrayData = json_decode($jsondata);
foreach($arrayData as $obj){
	echo "id:".$obj->food."<br />";
}

另外附上PHP两种解析json数据的方法:

在PHP代码中处理JSON 格式的字符串的两种方法:唯一不同已经highlight出来了

方法一:

$json ='[{"id":"1","name":"\u5f20\u96ea\u6885","age":"27","subject":"\u8ba1\u7b97\u673a\u79d1\u5b66\u4e0e\u6280\u672f"},{"id":"2","name":"\u5f20\u6c9b\u9716","age":"21","subject":"\u8f6f\u4ef6\u5de5\u7a0b"}]';
$students = json_decode($json);//得到的是 object
foreach($students as $obj){
echo "姓名:".$obj->name."年龄:".$obj->age." 专业:".$obj->subject."<br/>";
}


方法二:

$json ='[{"id":"1","name":"\u5f20\u96ea\u6885","age":"27","subject":"\u8ba1\u7b97\u673a\u79d1\u5b66\u4e0e\u6280\u672f"},{"id":"2","name":"\u5f20\u6c9b\u9716","age":"21","subject":"\u8f6f\u4ef6\u5de5\u7a0b"}]';
$students = json_decode($json, true);//得到的是 array
for($i=0;$i<count($students);$i++){
echo "姓名:".$students[$i]['name']."年龄:".$students[$i]['age']."专业:".$students[$i]['subject']."<br />";
}



  相关解决方案