将数据从php传递到Jquery [英] Passing data from php to Jquery

查看:301
本文介绍了将数据从php传递到Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将所有javascript / jquery代码放在一个文件中,并将其包含在我的页面中。没有apache进程js文件作为PHP什么是将数据从PHP传递到我的js脚本的最佳方法?现在我在我的页面上有一个隐藏的div,我回显了一个值然后使用jquery我得到文本内容然后拆分它来获取变量。这是一个很好的方式吗?或者有更好的方法吗?

I have all my javascript/jquery code in a file and include it into my page. Without having apache process js files as php what would be the best way to pass data from php to my js script? Right now I have a hidden div on my page that I echo out a value then using jquery I get the text content and then split it to get the variables. Is this a good way of doing it? Or is there a better way?

更新

如前所述,所有我的js代码在我包含在网页中的.js文件中。我可以在这种情况下使用PHP的唯一方法是告诉apache将.js文件视为php,这样就可以在.js文件中重新识别php代码。我不想这样做。

As mentioned prior, all my js code is in a .js file that I include into the webpage. The only way I could use php in this scenario is tell apache to treat .js files as php so it would recongize php code inside the .js file. I dont want to do this.

HTML

<div id="pagedata" style="display:none;">data1<>data2</div>

JS

var pagedata = $('#pagedata').text();
var break_data = pagedata.split('<>');


推荐答案

最佳做法可能是Matt在上述评论中提到的:使用JSON。如果您要使用jQuery,可以使用 $。get() $。getJSON()<来调用PHP脚本。 / code>。你可以在这里找到PHP JSON的手册: http://php.net/manual/en /book.json.php ,以及jQuery方法的API参考 $。getJSON()这里: http://api.jquery.com/jQuery.getJSON/

Best practice is likely as Matt mentions in the comment above: use JSON. If you're going to use jQuery, you can have a PHP script you call using either $.get() or $.getJSON(). You can find the manual for PHP JSON here: http://php.net/manual/en/book.json.php, and the API reference for the jQuery method $.getJSON() here: http://api.jquery.com/jQuery.getJSON/

HTH。

这篇关于将数据从php传递到Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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