简体   繁体   English

使用jquery通过php连接到服务器端SQL数据库

[英]Connecting to a server-side SQL database via php with jquery

I have been trying to look over an example to figure out how to connect to a server's SQL database from a client using JQuery, AJAX, and PHP, and though it is old it seems well done and straight forward: Example Link .A single folder contains all of my php files as well as the product version of jQuery (javascript-1.10.2.min.js). 我一直在试图查看一个例子来弄清楚如何使用JQuery,AJAX和PHP从客户端连接到服务器的SQL数据库,虽然它已经很久了但它似乎做得很好并且直截了当: 示例链接 。单个文件夹包含我的所有php文件以及jQuery的产品版本(javascript-1.10.2.min.js)。

Problem 3 - Fixed 问题3 - 修正

JS console shows [Object, "parsererror", SyntaxError] at JS控制台显示[Object,“parsererror”,SyntaxError]

var id = data.data[0];              //get id, data['data'][0] works here as well

in client.php. 在client.php中。 Object responseText shows ..."No Database Selected"... I have updated my client.php based on Daedalus' response and am still getting the same error. 对象responseText显示......“没有数据库选择”...我已根据Daedalus的响应更新了我的client.php,但仍然遇到同样的错误。

Error was in mislabeling a variable ($link instead of $con) in server-api.php 错误是在server-api.php中错误标记变量($ link而不是$ con)

-- Code -- - 代码 -

db-connect.php: DB-connect.php:

<?php 

//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "password";

$databaseName = "server-db";
$tableName = "inventory";

?>

server-api.php: 服务器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);

?>

client.php client.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>

Problem 1 - Fixed 问题1 - 修正

Thanks to user help, I have managed to get rid of my original error of: 感谢用户的帮助,我设法摆脱了原来的错误:

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.

Problem 2 - Fixed [now running on temporary web server (see link at bottom)] 问题2 - 修复[现在在临时Web服务器上运行(参见底部的链接)]

Now I am running WAMP (including phpmyadmin and apache) as my webserver. 现在我正在运行WAMP(包括phpmyadmin和apache)作为我的网络服务器。 I can run my php page with script (client.php) no problem, it runs, can't seem to find any errors in my logs. 我可以用脚本(client.php)运行我的php页面没问题,它运行,似乎无法在我的日志中找到任何错误。 However, I still never seem to hit the success function of my script. 但是,我似乎仍然没有达到我的脚本的成功功能。 I am assuming that I have inappropriately set something somewhere (eg localhost/"my site".php) but I am not sure where. 我假设我在某处不恰当地设置了某些东西(例如localhost /“我的网站”.php),但我不知道在哪里。

I also tried changing my AJAX function a bit, to include .done: 我也尝试过改变我的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");
});

but my output value never gets changed within the ajax call. 但我的输出值永远不会在ajax调用中改变。 I could be implementing .done incorrectly, but I just can't seem to figure out why I am not hitting anything and can't seem to find a log that is a help in finding the next step. 我可能会错误地实现.done,但我似乎无法弄清楚为什么我没有点击任何东西,似乎无法找到一个有助于找到下一步的日志。

On previous edit I removed localhost from php calls ('localhost/server-api.php' returned a 404) and now I am stuck again. 在之前的编辑中,我从php调用中删除了localhost('localhost / server-api.php'返回了404),现在我又被卡住了。 I get a 304 Not Modified from my jQuery call, but I thought that, as of jQuery 1.5 ajax handled this as a success so I should still be hitting my html text update (correct?) and I don't. 我从我的jQuery调用中获得了304 Not Modified,但我认为,从jQuery 1.5开始,ajax处理了这个成功,所以我仍然应该点击我的html文本更新(正确?)而我没有。

WAMP access Log: 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

Note - this is the only log that updates when I refresh client.php in my browser. 注意 - 这是我在浏览器中刷新client.php时唯一更新的日志。 my js console stays blank. 我的js控制台保持空白。 I have uploaded this to a temp site: zgc7009.99k.org/client-99k.php 我已将其上传到临时站点: zgc7009.99k.org/client-99k.php

Forgive me if the following is drawn out, but I wish to explain all that I can; 如果以下内容被抽出,请原谅我,但我希望尽我所能解释;

Firstly, as noted in comments, the error method of the jQuery .ajax() method only gets called if there is an error when the method attempts to load the requisite php page you(or it(if you don't specify a url, it uses the current page)) has specified. 首先,正如评论指出的那样, error了jQuery的方法.ajax()方法仅如果当方法尝试加载您所需的PHP页面错误被调用(或它(如果你没有指定URL,它使用当前页面))已指定。 An error in this regard would be something like a 404(page not found), 500(server error), or what-have-you. 这方面的错误可能是404(找不到页面),500(服务器错误)或者你有什么。

The current error you are experiencing is two-fold: 您遇到的当前错误有两方面:

  1. You are not running a server on your computer(or you are and aren't accessing the page via the correct url in your browser(it should be localhost/path/to/file.extension) 您没有在计算机上运行服务器(或者您是否通过浏览器中的正确URL访问该页面(它应该是localhost/path/to/file.extension)
  2. Same origin policy is preventing your page from even being loaded 同源策略阻止您的页面被加载

In regards to problem #1, a php page needs to be processed by your php interpreter, which you need to have installed on your system. 关于问题#1,需要由php解释器处理php页面,您需要在系统上安装该解释器。 I would recommend something like xampp to suit this case, though there are plenty others available. 我会推荐像xampp这样的东西来适应这种情况,尽管还有很多其他的可用。

When accessing a server which is running on your machine, one uses the localhost url in the address bar, no protocol( http:// , https:// , ftp:// ,etc), and never a file:/// protocol. 当访问在您的机器上运行的服务器时,使用地址栏中的localhost url,没有协议( http://https://ftp://等),而不是file:///协议。 For example, if I were to visit the folder test's index.php file, it would be localhost/test/index.php . 例如,如果我要访问文件夹test的index.php文件,那么它将是localhost/test/index.php

In regards to problem #2, browsers have various restrictions in place in order to prevent malicious code from executing.. One of these restrictions is the Same Origin policy , a policy which restricts documents of a differing origin than the originating request from accepting that request. 关于问题#2,浏览器有各种限制,以防止恶意代码执行。这些限制之一是同源策略 ,这是一种策略,它限制来源不同的文档而不是原始请求接受该请求。 For example.. 例如..

If we have a server at domain.website.com , and it makes a request to otherdomain.website.com , the request will fail as the endpoint of the request is on a different domain. 如果我们在domain.website.com有服务器,并且它向otherdomain.website.com发出请求,则请求将失败,因为请求的端点位于不同的域上。

Likewise, the same exists for any requests made in regards to a file:/// protocol.. It is always 1 treated as a different origin, and it will always 1 fail. 同样,相同的存在对于制造方面的任何请求file:///协议。它始终为1的产地不同对待,它总是会1次失败。 This behavior can be changed, but it is not recommended, as it is a security hole. 此行为可以更改,但不建议这样做,因为它是一个安全漏洞。

I also recommend you check out MDN's article on SOP . 我还建议您查看MDN关于SOP的文章

Of course, to fix all this.. install a web server(like xampp or wamp) on your machine(depending on your OS) or use a hosted web server, never open your html file by double clicking it, but by visiting its url(according to your webserver's directory(it differs per server)), and always make sure your domains and ports match. 当然,要修复所有这些..在您的机器上安装Web服务器(如xampp或wamp)(取决于您的操作系统)或使用托管的Web服务器,永远不要通过双击打开您的html文件,但访问其URL (根据您的网络服务器目录(每台服务器不同)),并始终确保您的域和端口匹配。

  • 1: Except in certain cases, such as here 1:除非在某些情况下,例如此处

Edit 1: 编辑1:

Don't know why I didn't see this before; 不知道为什么我之前没有看到这个; we could have avoided headaches.. anyway, firstly, change the error catching you do here: 我们本可以避免头痛..无论如何,首先,改变你在这里做的错误:

$dbs = mysql_select_db($databaseName, $con);
echo mysql_errno($con) . ": " . mysql_error($con). "\n";

To: 至:

$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));

And then, change your array set after your db handling to this: 然后,在数据库处理之后将数组设置更改为:

$result = mysql_query("SELECT * FROM $tableName");          //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result);

To explain what I've changed, and why.. Your first echo was causing the json parser to fail when parsing your echoed json. 解释我已经改变了什么,以及为什么..你的第一个回声是在解析你的回声json时导致json解析器失败。 If you didn't have your console open during your refresh, you wouldn't have seen that it did in fact execute the ajax request. 如果在刷新期间没有打开控制台,则不会看到它确实执行了ajax请求。 You also do not define an error handler, so you would have never known. 您也没有定义错误处理程序,因此您将从未知道。 In order to parse the new json I just created above, modify your success handler's variable declarations above into this: 为了解析我刚才创建的新json,将上面的成功处理程序的变量声明修改为:

var id = data.data[0];              //get id, data['data'][0] works here as well
var vname = data.data[1];           //get name

Of course, if your mysql causes any errors, you can then access those errors with the following: 当然,如果您的mysql导致任何错误,您可以使用以下内容访问这些错误:

console.log(data.mysql);

Again, in your success function. 再次,在你的成功功能。 To see if you have any errors with the actual .ajax() method or such, you can just do this for your error handler: 要查看实际的.ajax()方法是否有任何错误,您可以为错误处理程序执行此操作:

error: function() {
    console.log(arguments);
}

please you should start learning to PDO or Mysqli real fast, mysql_* will soon be depreciated, that is soonest, let me rewrite your query for you using PDO and prepared statements, you can kick it off from there. 请你开始快速学习PDO或Mysqli,mysql_ *很快就会被折旧,这是最快的,让我用PDO和预备语句为你重写你的查询,你可以从那里开始。

$connectionStr = 'mysql:host='.$host.';dbname='.$databaseName.'';   
$driverOptions = array();    

     $dbh = new PDO($connectionStr, $user, $pass, $driverOptions);              
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);     

     $query  =  $dbh->prepare("SELECT * FROM $tableName");
     $query->execute();

     $array = fetch(PDO::FETCH_OBJ); 

     echo json_encode($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM