带有javascript&的JSON概念的PHP [英] JSON concept with javascript & PHP

查看:57
本文介绍了带有javascript&的JSON概念的PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个人来阐明这个问题.

I need someone to shed some light on this subject.

当一个人进行AJAX调用时,该调用会调用一个php脚本,该脚本回显json_encode内容,以便javascript可以将其弄乱.注意:假设我们在php脚本中将标头设置为json.

When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.

javascript从php脚本接收的数据,我们是否必须使用eval或json的库进行解析?这是因为它将从php文件中接收到的数据视为文本而不是javascript吗?

The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Is it because it treats the data recieved from the php file as text and not as javascript?

我们可以在php脚本返回的数据上使用javascript点符号吗?还是在使用点符号之前必须将这些数据转换为javascript对象?

Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?

先谢谢您.

推荐答案

JSON只是一个字符串,它恰好符合对象的Javascript语法(因此缩写为:JavaScript Object Notation.)

JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)

要将其转换为Javascript对象,可以使用eval函数,但是为了提高安全性,建议使用现代浏览器中包含的JSON对象,或者使用您选择的Javascript库提供的函数:

To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:

var json = '{"thing":1, "thang":"two"}';

var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere

许多库还将作为Ajax请求的一部分为您处理转换. jQuery的用法如下:

Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:

jQuery.get('http://domain.com/path/to/request', function(obj)
{
    // string is automatically converted to an object,
    // usable as array or with dot notation
    alert(obj.thing);
    alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html

这篇关于带有javascript&的JSON概念的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆