Javascript 将数据从javascript发送到mysql数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8412505/
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
Send data from javascript to a mysql database
提问by Ciprian
I have this little click counter. I would like to include each click in a mysql table. Can anybody help?
我有这个小点击计数器。我想在 mysql 表中包含每次点击。有人可以帮忙吗?
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
document.write('<p>');
document.write('<a href="javascript:countClicks1();">Count</a>');
document.write('</p>');
document.write('<p id="p1">0</p>');
Just in case anybody wants to see what I did:
以防万一有人想看看我做了什么:
var count1 = 0;
function countClicks1() {
count1 = count1 + 1;
document.getElementById("p1").innerHTML = count1;
}
function doAjax()
$.ajax({
type: "POST",
url: "phpfile.php",
data: "name=name&location=location",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
document.write('</p>');
document.write('<a href="javascript:countClicks1(); doAjax();">Count</a>');
document.write('</p>');
document.write('<p id="p1">0</p>');
This is phpfile.php which for testing purposes writes the data to a txt file
这是用于测试目的的 phpfile.php 将数据写入 txt 文件
<?php
$name = $_POST['name'];
$location = $_POST['location'];
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $name);
fwrite($fh, $location);
fclose($fh);
?>
回答by Merlyn Morgan-Graham
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript,如您的问题中所定义,不能直接与 MySql 一起使用。这是因为它不在同一台计算机上运行。
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
JavaScript 运行在客户端(在浏览器中),数据库通常存在于服务器端。您可能需要使用中间服务器端语言(如 PHP、Java、.Net 或像 Node.js 这样的服务器端 JavaScript 堆栈)来执行查询。
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
这是一个关于如何编写一些将 PHP、JavaScript 和 MySql 绑定在一起的代码的教程,代码在浏览器和服务器上运行:
http://www.w3schools.com/php/php_ajax_database.asp
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
这是该页面的代码。它与您的场景并不完全匹配(它执行查询,并且不在数据库中存储数据),但它可能会帮助您开始了解您需要的交互类型,以便完成这项工作。
In particular, pay attention to these bits of code from that article.
特别要注意那篇文章中的这些代码。
Bits of Javascript:
一些 Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
PHP代码位:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
此外,在您了解此类代码的工作原理后,我建议您使用 jQuery JavaScript 库来执行 AJAX 调用。它比内置的 AJAX 支持更简洁、更易于处理,而且您不必编写特定于浏览器的代码,因为 jQuery 具有内置的跨浏览器支持。这是 jQuery AJAX API 文档的页面。
The code from the article
文章中的代码
HTML/Javascript code:
HTML/Javascript 代码:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
PHP代码:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
回答by Jan Han?i?
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorialon how to do the XHR request "by hand".
您必须以某种方式将此数据提交给服务器。我假设您不希望每次用户单击链接时都重新加载整个页面,因此您必须使用 XHR (AJAX)。如果您不使用 jQuery(或其他一些 JS 库),您可以阅读本教程,了解如何“手动”执行 XHR 请求。
回答by Dominic Green
The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.
其他海报是正确的,您无法直接从 javascript 连接到 MySQL。这是因为 JavaScript 在客户端,而 mysql 在服务器端。
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
所以你最好的选择是使用 ajax 调用上面引用的处理程序,如果你能让我们知道你的项目是什么语言,我们可以更好地帮助你,即 php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
如果您的项目使用的是 php,那么 Merlyn 的示例是一个很好的起点,我个人会使用 jquery.ajax() 来减少您的代码并有更好的机会减少跨浏览器问题。