我想触发php post到数据库脚本而不刷新页面(就像常规的php self一样)。
答案 0 :(得分:3)
查看jQuery $.post( )
功能。这是一个帮助您入门的链接:http://api.jquery.com/jQuery.post/
答案 1 :(得分:2)
我用它来做你想做的事:
function parseJsonIfPossible(code){
try {
return $.parseJSON(code);
} catch (e) {
return code;
}
}
function cmd(command,p1,p2,p3,p4,p5,p6){
return parseJsonIfPossible($.ajax({
url: core_url,
global: false,
type: "POST",
data: {command : command,p1:p1,p2:p2,p3:p3,p4:p4,p5:p5,p6:p6},
dataType: "html",
async:false,
success: function(msg){
//alert(msg);
}
}).responseText);
}
PHP:
function cmd()
{
$command = &$_POST['command'];
$p1 = &$_POST['p1'];$p2 = &$_POST['p2'];$p3 = &$_POST['p3'];$p4 = &$_POST['p4'];$p5 = &$_POST['p5'];$p6 = &$_POST['p6'];
if($command)echo($command($p1,$p2,$p3,$p4,$p5,$p6));
}
function test($i)
{
//simple
return mysql_query("UPDATE ... SET b='$i'");
//array
return json_encode(array(
mysql_query("UPDATE ... SET b='$i'"),
"fklsdnflsdnl",
));
}
用法(脚本):
$('#btn').click(function(){
var i = 99;
var result = cmd("test",i);
//simple
alert(result);
//array
console.log([result[0],result[1]]);
});
答案 2 :(得分:1)
以下是Ajax请求的基本示例代码。
function postData()
{
var xmlhttp;
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)
{
// Do anything you want with the response
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","page_to_be_post.php",true);
xmlhttp.send();
}
但是,您可以使用一些框架以较少的代码轻松完成此任务。
例如:
http://www.prototypejs.org/learn/introduction-to-ajax
http://api.jquery.com/jQuery.post/
还有更多可用的框架。
干杯!
答案 3 :(得分:1)
以下代码可能会帮助您使用jquery ajax进行php post。 假设您有一个带有id = form的表单和一个提交id = submit1的表单的按钮。 现在使用jquery ajax将表单数据发送到另一个页面,你需要在body结束之前使用以下代码。在编写下面的代码之前忘记附加jquery脚本。
$(document).ready(function(){
$('submit1').click(function(event){
//first stop the default submit action
event.preventDefault();
//now we will do some ajax
$.ajax({
url:'test.php',//the target page where to submit the data
type:'post',
cache:false,
data:$('#form').serialize(),//data to be sent from the form
dataType:'json',//expected data type from the server
error:function(xhr){
alert("the error is"+xhr.status);
}
})
//success function in terms of .done
.done(function(data){
alert("your data successfully submitted");
});
});
});