Including a php file dynamically with javascript and jquery

孤者浪人 提交于 2019-12-11 11:06:31

问题


I want to include a php file later(dynamically), rather than at the top. All this file does is get some contents from server and stores it in a javascript variable that i later use in jquery.

basically when you click the link, i get the info, then display it to save resources because there are many links that may not be used.

Should i just do $("body").load("phpfile.php"); ? this should work but I am trying to find a more proper way because it has nothing to do with html tag like body.


回答1:


You are approaching the problem in an odd way. Not to say it wouldn't work, just that you would have a hard time getting to. I would recommend using jquery's ajax with json.

Something like:

<div id="output"></div>

$(function ()
{
    //$.json('urltoRequestfrom?variable1=value1');
    $.post('/echo/json/',
           {json: '{"name":"test"}'},
           function (data)
           {
               $('#output').html(data["name"]); //first json object
           },'json');
});



回答2:


Why would you want to do this?

jQuery does indeed have a load function where you can fetch a page fragment, which is an ajax call, just use AJAX to fetch the data dynamically whenever you want, javascript can be configured to handle the data fetched however and whenever you want.

Also include a better description of your objective, as what you have described is very unclear.

Thanks and good luck,

h




回答3:


Always expect the worst from your visitors. If it where possible to include a php file with javascript, it would be a huge risk.

PHP is a server side language, and is not present in the browser. Javascript is a clientside language, and does not know anything about the PHP, only about the outputted HTML.

Use an AJAX call instead, check this page for more info: http://api.jquery.com/jQuery.ajax/




回答4:


Simply, you can't. Php is ran server-side. But you could use AJAX or Jquery AJAX



来源:https://stackoverflow.com/questions/5954371/including-a-php-file-dynamically-with-javascript-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!