我一直在尝试查看一个示例,以了解如何使用 JQuery、AJAX 和 PHP 从客户端连接到服务器的 SQL 数据库,尽管它很旧,但看起来做得很好且简单:Example Link一个文件夹包含我的所有 php 文件以及 jQuery 产品版本 (javascript-1.10.2.min.js)。
问题 3 - 已修复
JS 控制台显示 [Object, "parsererror", SyntaxError] at
var id = data.data[0]; //get id, data['data'][0] works here as well
在 client.php 中。对象响应文本显示...“未选择数据库”...我已根据 Daedalus 的响应更新了我的 client.php,但仍然收到相同的错误。
在 server-api.php 中错误标记变量($link 而不是 $con)时出现错误
-- 代码--
db-connect.php:
<?php
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "password";
$databaseName = "server-db";
$tableName = "inventory";
?>
服务器-api.php:
<?php
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'db-connect-99k.php';
$con = mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db('zgc7009_99k_db', $con);
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
客户端.php
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
//dataType: 'json', //data format (comment out or get parsererror)
// Successful network connection
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
$('#error_code').html("Success!");
},
error: function() {
console.log(arguments);
}
});
});
</script>
</body>
</html>
问题 1 - 已修复
感谢用户的帮助,我已经设法摆脱了原来的错误:
OPTIONS file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery.js:8706
XMLHttpRequest cannot load file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
问题 2 - 已修复[现在在临时 Web 服务器上运行(请参阅底部的链接)]
现在我正在运行 WAMP(包括 phpmyadmin 和 apache)作为我的网络服务器。我可以使用脚本(client.php)运行我的 php 页面,没有问题,它运行,似乎在我的日志中找不到任何错误。但是,我似乎仍然没有达到脚本的成功功能。我假设我在某个地方不恰本地设置了某些内容(例如 localhost/“my site”.php),但我不确定在哪里。
我还尝试稍微更改我的 AJAX 函数,以包含 .done:
$.ajax({
url: 'localhost/server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
}
}).done(function() {
$('#output').html("AJAX complete");
});
但是我的输出值在ajax调用中永远不会改变。我可能错误地实现了 .done,但我似乎无法弄清楚为什么我没有命中任何内容,并且似乎无法找到有助于找到下一步的日志。
在之前的编辑中,我从 php 调用中删除了 localhost('localhost/server-api.php' 返回了 404),现在我再次陷入困境。我从 jQuery 调用中收到 304 Not Modified,但我认为,从 jQuery 1.5 开始,ajax 已成功处理此问题,因此我仍然应该点击我的 html 文本更新(正确吗?),但我没有。
WAMP访问日志:
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /client.php HTTP/1.1" 200 2146
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /server-api.php HTTP/1.1" 200 38
注意 - 这是当我在浏览器中刷新 client.php 时更新的唯一日志。我的 js 控制台保持空白。我已将其上传到临时站点:zgc7009.99k.org/client-99k.php
最佳答案
如果以下内容冗长,请原谅我,但我想解释我能解释的一切;
首先,正如评论中所述,jQuery .ajax()
的 error
方法仅当该方法尝试加载您(或它(如果您不指定 url,则它使用当前页面))指定的必需 php 页面时出现错误,该方法才会被调用。这方面的错误可能类似于 404(未找到页面)、500(服务器错误)或“what-have-you”。
您当前遇到的错误有两个:
- 您的计算机上没有运行服务器(或者您正在但没有通过浏览器中的正确网址访问该页面(应该是
localhost/path/to/file.extension)
- 同源政策甚至会阻止您的页面加载
关于问题 #1,php 页面需要由您的 php 解释器处理,您需要在系统上安装该解释器。我会推荐像 xampp 这样的东西为了适应这种情况,尽管还有很多其他可用的。
当访问您计算机上运行的服务器时,使用地址栏中的localhost
url,无协议(protocol)(http://
,https ://
、ftp://
等),而不是 file:///
协议(protocol)。例如,如果我要访问文件夹 test 的 index.php 文件,它将是 localhost/test/index.php
。
关于问题#2,浏览器有各种限制,以防止恶意代码执行。这些限制之一是 Same Origin policy ,限制与原始请求来源不同的文档接受该请求的策略。例如..
如果我们在 domain.website.com
上有一个服务器,并且它向 otherdomain.website.com
发出请求,则该请求将失败,因为该请求的端点请求位于不同的域上。
同样,对于 file:///
协议(protocol)发出的任何请求也存在同样的情况。它始终被视为不同的来源1,并且它总会1失败。此行为可以更改,但不建议这样做,因为这是一个安全漏洞。
I also recommend you check out MDN's article on SOP .
当然,要解决这一切..在您的计算机上安装 Web 服务器(如 xampp 或 wamp)(取决于您的操作系统)或使用托管 Web 服务器,切勿通过双击打开 html 文件,而是通过访问其网址(根据您的网络服务器目录(每个服务器不同)),并始终确保您的域和端口匹配。
- 1:某些情况除外,例如here
编辑1:
不知道为什么我以前没有看到这个;我们本来可以避免头痛..无论如何,首先,更改您在此处执行的错误:
$dbs = mysql_select_db($databaseName, $con);
echo mysql_errno($con) . ": " . mysql_error($con). "\n";
致:
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
然后,在数据库处理后将数组集更改为:
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result);
解释我更改的内容以及原因..您的第一个 echo 导致 json 解析器在解析您的 echoed json 时失败。如果您在刷新期间没有打开控制台,您将看不到它实际上执行了 ajax 请求。您也没有定义错误处理程序,因此您永远不会知道。为了解析我上面刚刚创建的新 json,请将上面的成功处理程序的变量声明修改为:
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
当然,如果您的 mysql 导致任何错误,您可以使用以下命令访问这些错误:
console.log(data.mysql);
再次,在你的成功函数中。要查看实际的 .ajax()
方法等是否有任何错误,您可以对错误处理程序执行以下操作:
error: function() {
console.log(arguments);
}
关于javascript - 通过 php 和 jquery 连接到服务器端 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21103313/