将数据从javascript发送到mysql数据库

2021-11-20 00:00:00 javascript mysql

我有这个小小的点击计数器.我想在 mysql 表中包含每次点击.有人可以帮忙吗?

var count1 = 0;函数 countClicks1() {计数 1 = 计数 1 + 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>');

以防万一有人想看看我做了什么:

var count1 = 0;函数 countClicks1() {计数 1 = 计数 1 + 1;document.getElementById("p1").innerHTML = count1;}函数 doAjax()$.ajax({类型:POST",url: "phpfile.php",数据:名称=名称&位置=位置",成功:功能(味精){alert("数据保存:" + msg );}});}document.write('</p>');document.write('<a href="javascript:countClicks1(); doAjax();">Count</a>');document.write('</p>');document.write('<p id="p1">0</p>');

这是用于测试目的的 phpfile.php 将数据写入 txt 文件

解决方案

JavaScript,如您的问题中所定义,不能直接与 MySql 一起使用.这是因为它不在同一台计算机上运行.

JavaScript 运行在客户端(在浏览器中),数据库通常存在于服务器端.您可能需要使用中间服务器端语言(如 PHP、Java、.Net 或服务器端 JavaScript 堆栈,如 Node.js)来执行查询.

这里有一个教程,介绍如何编写一些将 PHP、JavaScript 和 MySql 绑定在一起的代码,代码在浏览器和服务器上运行:

http://www.w3schools.com/php/php_ajax_database.asp

这是该页面的代码.它与您的场景并不完全匹配(它执行查询,并且不在数据库中存储数据),但它可能会帮助您开始了解您需要的交互类型,以便完成这项工作.

特别要注意那篇文章中的这些代码.

Javascript 代码:

xmlhttp.open("GET","getuser.php?q="+str,true);xmlhttp.send();

PHP 代码:

mysql_select_db("ajax_demo", $con);$result = mysql_query($sql);//...$row = mysql_fetch_array($result)mysql_close($con);

此外,在您了解此类代码的工作原理后,我建议您使用 jQuery JavaScript 库来执行 AJAX调用.它比内置的 AJAX 支持更简洁、更容易处理,而且您不必编写特定于浏览器的代码,因为 jQuery 内置了跨浏览器支持.这是 jQuery AJAX API 文档.

文章中的代码

HTML/Javascript 代码:

<头><script type="text/javascript">函数 showUser(str){如果 (str==""){document.getElementById("txtHint").innerHTML="";返回;}如果(window.XMLHttpRequest){//IE7+, Firefox, Chrome, Opera, Safari 的代码xmlhttp=新的 XMLHttpRequest();}别的{//IE6、IE5代码xmlhttp=new ActiveXObject(Microsoft.XMLHTTP");}xmlhttp.onreadystatechange=function(){如果(xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("txtHint").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","getuser.php?q="+str,true);xmlhttp.send();}<身体><表格><选择名称=用户"onchange="showUser(this.value)"><option value="">选择一个人:</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></选择></表单><br/><div id="txtHint"><b>个人信息将在此处列出.</b></div>

PHP 代码:

I have this little click counter. I would like to include each click in a mysql table. Can anybody help?

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

<?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);
?>

解决方案

JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.

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.

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:

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:

xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();

Bits of PHP code:

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.

The code from the article

HTML/Javascript code:

<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
$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);
?>

相关文章