问问题
623 次
3 回答
4
您将在客户端 (JS) 上运行的代码与在服务器端 (PHP) 上运行的代码混淆了。JS 在 PHP 完成后运行 - 因此除非您提交表单 (POST/GET) 或使用 AJAX,否则您不能从 JS“调用”到 PHP 中的函数。
于 2013-01-16T22:32:58.240 回答
3
如果您只想通过单击按钮而不是刷新或重定向浏览器来执行此操作,则必须使用 $.ajax
1)阅读http://api.jquery.com/jQuery.ajax/
2)在你的按钮上添加一个事件处理程序 onclick="update();"
3)创建一个ajax的东西,如:
function request(variable1,variable2,variable3){
var request = $.ajax({
url: "/server.php", // The address of you php script that will handle the request
type: "POST", // Method type GET / POST in this case POST (Similar to form submission methods....)
data: { // What you send to the server 'VariableName' : VariableValue, in this case you assign the varaiables that were passed to the request function.
'var1': variable1,
'var2' : variable2,
'var3': variable3
},
dataType: "json" // The response type you expect from the server
})
request.done(function(msg) // Function being called when everything is ok and server sends back data
{
console.log(msg) // handle the reply / data
})
request.fail(function(jqXHR, textStatus) // Something went wrong...
{
console.log(textStatus); // See the error report
console.log(jqXHR);
})
request.complete(function(){
console.log("Ajax request complete!"); // This will always be executed when a request has completed even if it failed. (Executes after .done and .fail)
})
}
因此,您可以在每次单击按钮时调用的更新函数中执行此操作:
function update()
{
var val1 = $.('#selectbox').val();
var val2 = $.('#inputbox').val();
var val3 = $.('#textarea').val();
new request(val1,val2,val3);
}
请求/变量将使用 POST 方法发送,因此在您的 php 脚本中,您可以像处理表单一样处理它们
if(isset($_POST['var1']) && isset($_POST['var2']) && isset($_POST['var3']))
{
$serverReply = doThings($_POST['var1'],$_POST['var2'],$_POST['var3']);
//and this is how you reply to your client/browser in json format
echo json_encode($serverReply);
}
确保查看更多关于 ajax 通信的深度教程。网上有很多。
于 2013-01-16T22:57:28.570 回答
1
onclick 调用函数 javascript
函数 javascript 用 ajax 实现
例子:
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
于 2013-01-16T22:33:13.727 回答