使用 AJAX + jQuery + PHP 将数据发送到 MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20392036/
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 to MySQL with AJAX + jQuery + PHP
提问by abouletcouture
I've been looking all day to find a way to insert some data into my database and then show the new data in the list of already existent data on my webpage.
我一整天都在寻找一种方法来将一些数据插入到我的数据库中,然后在我的网页上已经存在的数据列表中显示新数据。
I know that some of the points I can't get done may be basics but I just started learning Javascript/ AJAX so I have a limited knowledge.
我知道我无法完成的一些要点可能是基础知识,但我刚刚开始学习 Javascript/AJAX,所以我的知识有限。
I think that 70% of the job is done, I can display the data on my webpage using AJAX/jQuery/PHP but I can't figure how to send data from a "textarea" to my database using again AJAX/jQuery/PHP.
我认为 70% 的工作已经完成,我可以使用 AJAX/jQuery/PHP 在我的网页上显示数据,但我无法弄清楚如何再次使用 AJAX/jQuery/PHP 将数据从“textarea”发送到我的数据库.
So far this is what I've done :
到目前为止,这就是我所做的:
index.php
In this page, I figure that I need to put an onClick: function() on the button but I don't know where to put that function and what it should exactly do.
index.php
在这个页面中,我认为我需要在按钮上放置一个 onClick: function() ,但我不知道将该函数放在哪里以及它应该做什么。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>TP2</title>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<script src="javascript.js"></script>
Message: <input type="text" id="message-content">
<input type="button" id="message-submit" value="Envoyer">
<div id="output" align="center">
</div>
</body>
</html>
javascript.js
This page contain the AJAX code that display my data in the #output div.
I just don't know what to put in "data: {}" so the content of my textarea is sent to my php file.
javascript.js
此页面包含在#output div 中显示我的数据的AJAX 代码。我只是不知道在 "data: {}" 中放什么,所以我的 textarea 的内容被发送到我的 php 文件。
$.ajax({
url: "messages.php",
type: "POST",
async: true,
data: { WHAT GOES HERE ? },
dataType: "html",
success: function(data) {
$('#output').html(data);
},
});
messages.php
I know that the INSERT query will go here but I can't figure how to get the value from the POST of my textarea.
messages.php
我知道 INSERT 查询会在这里进行,但我不知道如何从 textarea 的 POST 中获取值。
<?php
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "myDataBaseName";
$tableName = "comments";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName ORDER BY date DESC LIMIT 0 , 10 ");
$data = array();
while ($row = mysql_fetch_array($result))
{
echo $row['message']." - ".$row['date'];
echo "<br />";
}
?>
回答by Krish R
data: {'messagecontent': $("#message-content").val()},
回答by Raja Amer Khan
You can send anything in that property. Try this: js
您可以发送该属性中的任何内容。试试这个:js
$.ajax({
url: "messages.php",
type: "POST",
data: 'show=content',
success: function(data) {
$('#output').html(data);
},
});
messages.php
消息.php
if(isset($_POST['show']) && $_POST['show']=='content') {
// rest of your code goes here..
}
One more thing. Use MySQLi instead of MySQL as it's a deprecated extension now.
还有一件事。使用 MySQLi 而不是 MySQL,因为它现在是一个已弃用的扩展。
回答by JustinM151
you can use an onclick, or use a jQuery .click function for the button...
您可以使用 onclick,或使用 jQuery .click 功能按钮...
you would put this in script tags, usually in your head or inside the document.ready
你会把它放在脚本标签中,通常在你的头脑中或在 document.ready 中
$("#message-submit").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#message-content").val()!="") {
$.ajax({
url: "messages.php",
type: "POST",
async: true,
data: { message:$("#message-content").val() }, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
},
});
} else {
//notify the user they need to enter data
}
});
for messages.php, the value of your AJAX POST will now be available to your PHP in the variable $_POST['message']
对于messages.php,您的AJAX POST 的值现在将在变量 $_POST['message'] 中可供您的 PHP 使用
$sql = "INSERT INTO tableName (messages) VALUES ('".$_POST['messages']."')";
EDIT/UPDATE:Six years later my original answer received another up vote so I feel it is probably relevant to post an update that the above is now globally accepted as being incredibly insecure. The jQuery used should be placed at the end of your document in the $(document).ready() method or preferably loaded in from a single minified app.js file. That aside, you will likely want to incorporate some form of CSRF (Cross Site Request Forgery) token system to help keep bots from slamming your form with spam and potentially malicious data, which leads to the next point.
编辑/更新:六年后,我的原始答案又收到了一次投票,所以我觉得发布更新可能是相关的,上述内容现在被全球接受为非常不安全。使用的 jQuery 应该放在文档末尾的 $(document).ready() 方法中,或者最好从单个缩小的 app.js 文件中加载。除此之外,您可能希望合并某种形式的 CSRF(跨站点请求伪造)令牌系统,以帮助防止机器人用垃圾邮件和潜在的恶意数据抨击您的表单,这将导致下一点。
The SQL listed here takes the raw data from the post data and places it in the insert statement. At the bare minimum you should be sanitizing that data. If you are using mysqli you can use the mysqli::real_escape_string($str) static method (http://php.net/manual/en/mysqli.real-escape-string.php) to sanitize any user provided data being placed in the query.
此处列出的 SQL 从发布数据中获取原始数据并将其放入插入语句中。您至少应该清理这些数据。如果您使用 mysqli,您可以使用 mysqli::real_escape_string($str) 静态方法(http://php.net/manual/en/mysqli.real-escape-string.php)来清理任何用户提供的数据在查询中。
However, a much better method now would be to use prepared statements with PDO so that the data provided gets bound to query in such a way that it can only be used as intended. http://php.net/manual/en/pdo.prepare.php
但是,现在更好的方法是将准备好的语句与 PDO 一起使用,以便提供的数据以只能按预期使用的方式绑定到查询。http://php.net/manual/en/pdo.prepare.php
回答by KennyPowers
Here's what Doc says:
这是 Doc 所说的:
dataType: PlainObject or String
数据类型:PlainObject 或 String
A plain object or string that is sent to the server with the request.
随请求发送到服务器的普通对象或字符串。
Here's some infor about Plain Object: http://api.jquery.com/Types/#PlainObject
这里有一些关于普通对象的信息:http: //api.jquery.com/Types/#PlainObject
See the next example of usage:
请参阅下一个用法示例:
var formData = "name=ravi&age=31"; //Name value Pair
or
或者
var formData = {name:"ravi",age:"31"}; //Array
$.ajax({
url : "messages.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
},
});
回答by Ricardo G
I was able to get the above code working with a link instead of a input type text box and button with those adjustments:
通过这些调整,我能够使用链接而不是输入类型文本框和按钮使上述代码工作:
<script type="text/javascript">
function msg(intValue) {
var x = intValue;
$.ajax({
url: "messages.php",
type: "POST",
data: 'message=' + x,
success: function(data) {
$('#output').html(data);
},
});
}
</script>
on the link I had:
在我的链接上:
<a href="#" id="message-content" onclick="msg('fl')">Florida</a>
回答by CodeBreaker
Try this.Its working
试试这个。它的工作
<script>
$("#message-submit").click(function() {
var senddata = $('#message-content').val();
console.log(senddata);
$.ajax({
type: "post",
url: "messages.php",
dataType: 'json',
data: {message:senddata},//for multiple data you can use
//{message:senddata,id:user_id}etc
success: function(data) {
console.log(data);
}
});
});
</script>

