用 JavaScript 连接 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4483821/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting Php with javascript
提问by sammville
I am trying to make a plugin that people can place on their site to generate a form. I dont want to use an iframe to display the form but use javascript to generate it.
我正在尝试制作一个插件,人们可以将其放置在他们的网站上以生成表单。我不想使用 iframe 来显示表单,而是使用 javascript 来生成它。
The problem is how do i connect the javascript and php together. My site is programmed in PHP.
问题是我如何将 javascript 和 php 连接在一起。我的网站是用 PHP 编程的。
采纳答案by marekventur
Your getting a liite mixed up, I think.
我想你有点搞混了。
PHP runs on your server. This is the place where you fetch data from the database and create some form of html-response.
PHP 在您的服务器上运行。这是您从数据库中获取数据并创建某种形式的 html 响应的地方。
Javascript runs in the browser. It can't directly talk to your database.
Javascript 在浏览器中运行。它不能直接与您的数据库对话。
iframe is a special html-element: Therfore it is passive and can't do anything like creating a form.
iframe 是一个特殊的 html 元素:因此它是被动的,不能做任何事情,比如创建一个表单。
You have two ways:
你有两种方法:
- Create a PHP script which handles everything through plain HTTP-Requests. This is the "old school" way and requires a lot of page-reloading.
 - Write most of the logic in javascript and let it communicate to PHP/your database through AJAX. In this case. Have a look at jQuerywhich makes AJAX-requests (and a lot of other things) very easy.
 
回答by Jakub
One issue you will be faced with is 'Cross site Scripting' with Javascript / AJAX. You can read up on it a bit here:
您将面临的一个问题是使用 Javascript / AJAX 的“跨站点脚本”。你可以在这里阅读一下:
http://snook.ca/archives/javascript/cross_domain_aj
http://snook.ca/archives/javascript/cross_domain_aj
Also, thinking your process through, you will need sufficient javascript code to create a 'widget' on any place, and have a way to communicate BACK to your server (keep in mind PHP only runs local on your machine, so it cannot be used remotely in your javascript).
此外,仔细考虑您的过程,您将需要足够的 javascript 代码来在任何地方创建一个“小部件”,并有一种方式与您的服务器进行通信(请记住,PHP 仅在您的机器上本地运行,因此无法使用)远程在您的 javascript 中)。
You will probably need to build a JSON API (google / stack search this if needed). And enable communication from your JAVASCRIPT to the API (don't think of it as to PHP, even tho php will be your API server side language).
您可能需要构建一个 JSON API(如果需要,请使用谷歌/堆栈搜索)。并启用从您的 JAVASCRIPT 到 API 的通信(不要将其视为 PHP,即使 php 将是您的 API 服务器端语言)。
Here is an example of a PHP JSON API (on youtube too):
这是 PHP JSON API 的示例(也在 youtube 上):
回答by seriousdev
If you put PHP into JavaScript and someone implements this, PHP will compile on their server. So you just can't. You just need to put the form in your plugin.
如果您将 PHP 放入 JavaScript 并且有人实现了这一点,那么 PHP 将在他们的服务器上编译。所以你不能。你只需要把表格放在你的插件中。

