Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

javascript - Passing data from php to 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?

UPDATE

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('<>');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why don't you just have php render javascript directly (as JSON), then you have it available to jQuery natively.

<script>

  var data =  {my: 'data', goes: 'here', <? echo render_more_of_my_data(); ?> };

</script>

Edit:

if you don't want to have inline js in your php page, and don't want apache to process js as php, then maybe you can src a php file which contains js.

<script src="my_php_file.php">

and inside that php file have js

var data = <? echo render_my_data(); ?>;

OR

just jQuery to call a php webservice using ajax jQuery.get("php_url.php"), and again in that php script you render some json.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...