如何通过javascript执行php
How to execute php through javascript
我目前正在使用 PHP 和 Backbone.js,在某些地方我正在使用 PHP 与我的 MySQL 服务器交互,并用 [=24] 填充前端=].
这是我正在尝试执行的示例 PHP。
$query="select id,username,message,useremail,date from contact";
$result =mysqli_query($connection,$query);
if ($result) {
echo '<table id="hor-minimalist-b" summary="Users List">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col">User Name</th>
<th scope="col">User Message</th>
<th scope="col">User Email</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>';
while($resultarray=mysqli_fetch_array($result)){
echo "
<tr>
<td>{$resultarray['0']}</td>
<td>{$resultarray['1']}</td>
<td>{$resultarray['2']}</td>
<td>{$resultarray['3']}</td>
<td>{$resultarray['4']}</td>
</tr>
";
}
echo "</tbody>
</table>";
}
一种方法是制作一个 PHP 文件并发出 ajax 请求以获取 HTML 输出并附加到 div
容器中。但是由于我有太多 PHP 代码片段,我想以某种方式使用 javascript 来减轻我的负担,因为我正在实施 backbone (http://myurl/#link/feed).
目前,我尝试了一种丑陋的方式:使用 HTML 并通过 PHP 的 echo
.
调用 javascript 函数
简短的回答是:你不能。
PHP 在服务器上执行,JavaScript 在客户端执行。一旦页面到达浏览器,所有 PHP 都已被解释。最好的选择是 AJAX 请求 returns JSON 的服务,然后使用 JavaScript.
处理和显示
如果我没理解错的话,您希望在某些地方使用 PHP 加载网页的某些部分。可以做到,但根据我的经验,这很复杂,而且并不理想。这是您可以执行的操作的非代码说明。
- 使用 PHP 呈现您的 HTML/JavaScript 页面。 (example.php)
- 有一个使用 Ajax 调用 PHP 页面的 JavaScript 函数。您调用的 PHP 页面应该只回显您想要动态创建的所有 HTML。您可以创建一个大字符串变量,并在您准备好 return 后回显它。回显将 returned 到 JavaScript 的 Ajax 调用。 (example_ajax.php 生成你想要的 HTML 并将其回显)
- 根据需要使用从 example_ajax.php 收到的回复 JavaScript 来更新您的页面。
我的评论摘要:
Gradually integrating Backbone into an existing PHP website is
shooting yourself in the foot. Backbone shines when used correctly
within a single-page app feeding its data from a RESTful API.
What you would need is to make a REST API with PHP, exposing your data
from the server through different url endpoints used by backbone models
and collections. PHP can return anything, it's not limited to HTML, so
you could return JSON which javascript can easily parse.
如何将 Backbone 与 PHP
一起使用
后端API
这是一个基于您的代码的非常简单的 PHP 端点。
example_ajax.php
<?php
$query ="select id,username,message,useremail,date from contact";
$result = mysqli_query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// return the array as JSON so Backbone can automatically parse it.
print json_encode($rows);
见Creating a simple REST API in PHP
有 PHP 框架可以为您处理 REST API,例如:
前端数据处理
创建绑定到我们新创建的端点的自定义集合:
var ContactCollection = Backbone.Collection.extend({
url: "example_ajax.php",
});
静态模板
并使用 Backbone 视图处理 HTML 模板。
首先准备HTML模板,可以是服务器上的静态HTML。
<table id="hor-minimalist-b" summary="Users List">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col">User Name</th>
<th scope="col">User Message</th>
<th scope="col">User Email</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/template" id="contact-template">
<td><%= id %></td>
<td><%= username %></td>
<td><%= message %></td>
<td><%= useremail %></td>
<td><%= date %></td>
</script>
Backbone 观看次数
那么浏览量:
var ContactView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#contact-template').html()),
initialize: function(options){
// optional, automatically remove the html of this row only.
this.listenTo(this.model, 'remove', this.remove);
},
render: function() {
this.$el.empty().append(this.template(this.model.toJSON()));
return this;
},
});
下面的列表视图使用 ContactView
作为子视图。
var ContactListView = Backbone.View.extend({
el: "#hor-minimalist-b", // uses existing element in the page
initialize: function(options) {
// cache a jQuery element to use as a container for the child views.
this.$body = this.$('tbody');
// optional, automatically adds a new contact when the collection changes
this.listenTo(this.collection, 'add', this.renderContact);
},
render: function() {
this.$body.empty();
this.collection.each(this.renderContact, this);
return this; // always return this for chaining
},
renderContact: function(model) {
var view = new ContactView({ model: model });
this.$body.append(view.render().el);
},
});
如何使用
var collection = new ContactCollection(),
view = new ContactListView({ collection: collection });
view.render();
collection.fetch();
.fetch()
函数对类似 http://www.example.com/example_ajax.php
的对象进行 GET 调用,它应该 return 一个数组。
为什么是 API?为什么不从 JavaScript 发送 SQL 查询?
JavaScript 在客户端运行,您应该永远不要信任。相反,您在服务器上公开了您可以信任的特定端点。这就是为什么你需要 API.
从 javascript 发送 SQL 查询是个坏主意,原因如下:
- SQL Injection:有人可以 fetch/change 您数据库中的任何内容(包括窃取密码,或一起破坏数据库),
- 这是通往您的服务器的大门,
- 缺乏可信的验证,或者更难验证 SQL 查询字符串,
- 紧耦合,例如使得在不同客户端(移动应用程序、网站、桌面应用程序等)之间共享查询代码变得更加困难
可以做到,但不应该。
phpMyAdmin 是一个应用程序示例,它采用用户编写的 SQL 并按原样运行。
如果它处于受控环境中,例如本地 Intranet,并且您想从客户端 JavaScript 访问 MySQL,您可以编写一个 php 脚本,它采用请求正文并将其直接传递给 MySQL 数据库,return 将结果作为 JSON.
例如,有一个名为 Squel.js 的库用于构建 SQL 查询字符串。他们在首页上有一个大红框,上面写着:
NOTE: It is recommended that you do NOT create queries browser-side to
run on the server as this massively increases your exposure to SQL Injection attacks.
补充阅读:
- Is there any reason not to go directly from client-side Javascript to a database?
- Can JavaScript connect with MySQL?
- What exactly is RESTful programming?
- Best Practices for Designing a Pragmatic RESTful API
我目前正在使用 PHP 和 Backbone.js,在某些地方我正在使用 PHP 与我的 MySQL 服务器交互,并用 [=24] 填充前端=].
这是我正在尝试执行的示例 PHP。
$query="select id,username,message,useremail,date from contact";
$result =mysqli_query($connection,$query);
if ($result) {
echo '<table id="hor-minimalist-b" summary="Users List">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col">User Name</th>
<th scope="col">User Message</th>
<th scope="col">User Email</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>';
while($resultarray=mysqli_fetch_array($result)){
echo "
<tr>
<td>{$resultarray['0']}</td>
<td>{$resultarray['1']}</td>
<td>{$resultarray['2']}</td>
<td>{$resultarray['3']}</td>
<td>{$resultarray['4']}</td>
</tr>
";
}
echo "</tbody>
</table>";
}
一种方法是制作一个 PHP 文件并发出 ajax 请求以获取 HTML 输出并附加到 div
容器中。但是由于我有太多 PHP 代码片段,我想以某种方式使用 javascript 来减轻我的负担,因为我正在实施 backbone (http://myurl/#link/feed).
目前,我尝试了一种丑陋的方式:使用 HTML 并通过 PHP 的 echo
.
简短的回答是:你不能。
PHP 在服务器上执行,JavaScript 在客户端执行。一旦页面到达浏览器,所有 PHP 都已被解释。最好的选择是 AJAX 请求 returns JSON 的服务,然后使用 JavaScript.
处理和显示如果我没理解错的话,您希望在某些地方使用 PHP 加载网页的某些部分。可以做到,但根据我的经验,这很复杂,而且并不理想。这是您可以执行的操作的非代码说明。
- 使用 PHP 呈现您的 HTML/JavaScript 页面。 (example.php)
- 有一个使用 Ajax 调用 PHP 页面的 JavaScript 函数。您调用的 PHP 页面应该只回显您想要动态创建的所有 HTML。您可以创建一个大字符串变量,并在您准备好 return 后回显它。回显将 returned 到 JavaScript 的 Ajax 调用。 (example_ajax.php 生成你想要的 HTML 并将其回显)
- 根据需要使用从 example_ajax.php 收到的回复 JavaScript 来更新您的页面。
我的评论摘要:
Gradually integrating Backbone into an existing PHP website is shooting yourself in the foot. Backbone shines when used correctly within a single-page app feeding its data from a RESTful API.
What you would need is to make a REST API with PHP, exposing your data from the server through different url endpoints used by backbone models and collections. PHP can return anything, it's not limited to HTML, so you could return JSON which javascript can easily parse.
如何将 Backbone 与 PHP
一起使用后端API
这是一个基于您的代码的非常简单的 PHP 端点。
example_ajax.php
<?php
$query ="select id,username,message,useremail,date from contact";
$result = mysqli_query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// return the array as JSON so Backbone can automatically parse it.
print json_encode($rows);
见Creating a simple REST API in PHP
有 PHP 框架可以为您处理 REST API,例如:
前端数据处理
创建绑定到我们新创建的端点的自定义集合:
var ContactCollection = Backbone.Collection.extend({
url: "example_ajax.php",
});
静态模板
并使用 Backbone 视图处理 HTML 模板。
首先准备HTML模板,可以是服务器上的静态HTML。
<table id="hor-minimalist-b" summary="Users List">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col">User Name</th>
<th scope="col">User Message</th>
<th scope="col">User Email</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/template" id="contact-template">
<td><%= id %></td>
<td><%= username %></td>
<td><%= message %></td>
<td><%= useremail %></td>
<td><%= date %></td>
</script>
Backbone 观看次数
那么浏览量:
var ContactView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#contact-template').html()),
initialize: function(options){
// optional, automatically remove the html of this row only.
this.listenTo(this.model, 'remove', this.remove);
},
render: function() {
this.$el.empty().append(this.template(this.model.toJSON()));
return this;
},
});
下面的列表视图使用 ContactView
作为子视图。
var ContactListView = Backbone.View.extend({
el: "#hor-minimalist-b", // uses existing element in the page
initialize: function(options) {
// cache a jQuery element to use as a container for the child views.
this.$body = this.$('tbody');
// optional, automatically adds a new contact when the collection changes
this.listenTo(this.collection, 'add', this.renderContact);
},
render: function() {
this.$body.empty();
this.collection.each(this.renderContact, this);
return this; // always return this for chaining
},
renderContact: function(model) {
var view = new ContactView({ model: model });
this.$body.append(view.render().el);
},
});
如何使用
var collection = new ContactCollection(),
view = new ContactListView({ collection: collection });
view.render();
collection.fetch();
.fetch()
函数对类似 http://www.example.com/example_ajax.php
的对象进行 GET 调用,它应该 return 一个数组。
为什么是 API?为什么不从 JavaScript 发送 SQL 查询?
JavaScript 在客户端运行,您应该永远不要信任。相反,您在服务器上公开了您可以信任的特定端点。这就是为什么你需要 API.
从 javascript 发送 SQL 查询是个坏主意,原因如下:
- SQL Injection:有人可以 fetch/change 您数据库中的任何内容(包括窃取密码,或一起破坏数据库),
- 这是通往您的服务器的大门,
- 缺乏可信的验证,或者更难验证 SQL 查询字符串,
- 紧耦合,例如使得在不同客户端(移动应用程序、网站、桌面应用程序等)之间共享查询代码变得更加困难
可以做到,但不应该。
phpMyAdmin 是一个应用程序示例,它采用用户编写的 SQL 并按原样运行。
如果它处于受控环境中,例如本地 Intranet,并且您想从客户端 JavaScript 访问 MySQL,您可以编写一个 php 脚本,它采用请求正文并将其直接传递给 MySQL 数据库,return 将结果作为 JSON.
例如,有一个名为 Squel.js 的库用于构建 SQL 查询字符串。他们在首页上有一个大红框,上面写着:
NOTE: It is recommended that you do NOT create queries browser-side to run on the server as this massively increases your exposure to SQL Injection attacks.
补充阅读:
- Is there any reason not to go directly from client-side Javascript to a database?
- Can JavaScript connect with MySQL?
- What exactly is RESTful programming?
- Best Practices for Designing a Pragmatic RESTful API