当前位置: 动力学知识库 > 问答 > 编程问答 >

How to structure PHP AJAX functions within a web application?

问题描述:

I work for a small company (read: three employees) that develops web applications, and we've been consistently using this structure for each page of our apps:

  • PHP page 'placeholder' that sets up the environment.
  • HTML seperated into a Smarty .tpl file.
  • JavaScript separated into a different .js file.
  • And a 'ajax_functions.php' file to be posted to by the JavaScript.

I feel pretty good about the file structure, although it is a bit messy (and if I'm wrong, please let me know!). My question is specifically about that 'ajax_functions.php' page. Right now the JavaScript will make a $.post request to something along the lines of 'ajax_functions.php?action=subscribe', and the page itself looks like this:

 switch($_GET['action']){

case('subscribe'):

//Do stuff...

break;

default:

die('Invalid request');

}

I just feel this way is too insecure: if someone wants to link directly to the page and repeatedly spam it with info, there's little way to stop them. Is there perhaps a better to structure the requests?

网友答案:

This seems pretty good.

For contrast heres what I do (pretty similar)

My structure

-A JS file for the AJAX etc

-A PHP classe / functions that process the _POST and _GET data

Thats it really.

The class / functions check for the correct _POST or _GET data and do any other validation checks I need.

From the functions I return a array, which can then be json_encoded and sent back to the JS

This works well for me because the functions can be used for forms that send the same data.

分享给朋友:
您可能感兴趣的文章:
随机阅读: