I have just started into OO PHP and have created my first class. As it is, it works, but I want to tidy things up a bit.
Right now elements in the class call an ajax function that is declared in 开发者_StackOverflow社区the head of the document.
I don't want the class to be dependent on a proper head, so to keep it self contained, I moved the script functions into the class file. I could not find information on whether this is a no-no, so if it is, I want to know "Why is putting javascript/ajax in a PHP class bad form?" If, however, it is an acceptable practice, I have a trickier question.
The AJAX calls a PHP page who's results will then fill in more of the class object on the page. But, I figure the class would be better if it didn't rely on external php files either. So, I moved the files into functions on the class file. Here's the tricky bit.
How do I get the AJAX to get the results from a function located on the same file as the AJAX call instead of an external page?
Here is my AJAX code so far. var url currently is the path to one of two possible PHP pages instead of the desired internal php functions. var dest is where in the class object the results end up.
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq(url,dest) {
http.open('get',url);
http.onreadystatechange = function () {
if (http.readyState == 4) {
if (http.status == 200) {
var responce = http.responseText;
document.getElementById(dest).innerHTML = responce;
}
}
};
http.send(null);
}
What you're asking for sounds like xml-rpc or json-rcp. It lets you dynamically execute server-side code and get the results.
Example javascript rpc library: http://barracudaserver.com/doc/WebServices/JRpcDoc.html
However, I think that simply passing parameters is what you want. The simplest way is to pass get parameters in the url
http://www.site.com/ajax.php?cmd=find_user&user_id=12
then in php check for those parameters in the global $_GET
variable
if(isset($_GET["cmd"]) && $_GET["cmd"] == "find_user"){
$user_id = $_GET["user_id"];
//some server-side stuff
echo results;
}
精彩评论