使用POST或GET的Javascript / AJAX到PHP页面 [英] Javascript/AJAX to PHP Page with either POST or GET
问题描述
我有一个带有2个值的javascript函数。我想将这些值发布到一个PHP页面,我可以用它更新一个mySQL数据库。这是我到目前为止,这是行不通的。
函数updateDB(page1,page2)
{
alert(TEST);
$ .ajax({
type:'POST',
url:update.php,
page1:page1,
page2:page2
});
}
Update.php代码
<?php includeconnect.php;
$ page1 = $ _POST ['page1'];
$ page2 = $ _POST ['page2'];
mysql_query(UPDATE`pages` SET`page1` ='$ page1');
?>
当我运行这个函数时,我得到一个POP,但是数据库没有更新。
有什么建议吗?我不介意使用GET或POST。
预先感谢,
发送数据的正确方法通过POST与jQuery使用 data
property。
一个例子是:
$ p $ function updateDB(page1 ,第2页)
{
$ .ajax({
type:'POST',
url:'update.php',
data:{
page1:page1,
page2:page2
},
成功:function(){
window.location =http://google.com;
} ,
cache:false
});
}
我还添加了警报$ c $成功,以及禁用缓存。即使这是后,IE会缓存发送请求到页面请求与get。
我强烈建议使用MySQLi,或在至少转义查询:
includeconnect.php;
$ page1 = mysql_real_escape_string($ _ POST ['page1']);
$ page2 = mysql_real_escape_string($ _ POST ['page2']);
$ b $ mysql_query(UPDATE`pages` SET`page1` ='$ page1')或die(mysql_error());
如果您想从href之后更改页面,请执行以下操作:
< script>
函数linkme(_this){
window.event.preventDefault();
//用ajax
做所有的代码window.location = _this.href;
}
< / script>
< a href =http://google.comonclick =linkme(this)> Clicky< / a>
I have a javascript function with 2 values. I want to post those values to a PHP page where I can update a mySQL database with it. Here is what I have so far, which doesn't work.
function updateDB(page1,page2)
{
alert("TEST");
$.ajax({
type: 'POST',
url: update.php,
page1: page1,
page2: page2
});
}
Update.php code
<?php include "connect.php";
$page1 = $_POST['page1'];
$page2 = $_POST['page2'];
mysql_query("UPDATE `pages` SET `page1` = '$page1'");
?>
When I run the function, I get a POP up but the database does not update.
Any suggestions? I don't mind using GET or POST.
Thanks in advance,
The correct way to send data via POST with jQuery is with the data
property.
An example is:
function updateDB(page1,page2)
{
$.ajax({
type: 'POST',
url: 'update.php',
data: {
page1: page1,
page2: page2
},
success: function() {
window.location = "http://google.com";
},
cache: false
});
}
I have also added alert
on success, as well as disabling cache. Even though this is post, IE will cache post requests to pages that have been requested with get.
I would highly recommend using MySQLi, or at the very least escaping the query:
include "connect.php";
$page1 = mysql_real_escape_string($_POST['page1']);
$page2 = mysql_real_escape_string($_POST['page2']);
mysql_query("UPDATE `pages` SET `page1` = '$page1'") or die(mysql_error());
If you want to change the page afterwards from the href simply do this:
<script>
function linkme(_this) {
window.event.preventDefault();
//do all the code with ajax
window.location = _this.href;
}
</script>
<a href="http://google.com" onclick="linkme(this)">Clicky</a>
这篇关于使用POST或GET的Javascript / AJAX到PHP页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!