我有一个PHP脚本,我想传入一个值。所以example.com/test.php?command=apple
。如果已输入,则执行其代码。这一切都在服务器端工作,但我如何使用ajax调用来实现这一目标?
我的代码:
PHP:
<?php
if ($_GET['command']=='apples')
{
//do code
echo "hello";
}
?>
Jquery的:
$.ajax({
url : '../command/test.php?command=apples'
}).done(function(data) {
console.log("result: " + data);
});
答案 0 :(得分:2)
您可以将POST
请求中的值发送到php
页面,并使用$.ajax
例如,我们将计算2个数字并通过ajax
$.ajax({
url: "/path/to/page.php",
type: "POST",
data: {number_1: 10, number_2: 5},
success: function(response){
// alert $result from the php page which is called response here.
alert(response);
}
});
// checking if data exists
if ($_POST['variable_1'] != null && $_POST['variable_2'] != null ){
$variable_1 = $_POST['variable_1'];
$variable_2 = $_POST['variable_2'];
$result = $variable_1 + $variable_2;
}else{
// either of the values doesn't exist
$result = "No Data Was Sent !";
}
// returning $result which is either 15 or " no data was sent "
echo $result;
这将返回15
。希望现在有意义。
答案 1 :(得分:2)
您可以将数据放入数据部分,我认为这将解决您的问题。
$.ajax({
url : '../command/test.php',
data: {command: "apples",login: "succes"}
}).done(function(data) {
console.log("result: " + data);
});
此外,您可以看到作为回复获得的内容,打开开发人员工具,您可以在network
下看到您的请求出现时,点击该按钮即可看到响应。
答案 2 :(得分:2)
下面的代码段非常直观且不言自明......但如果您有任何疑问,请不要犹豫,使用此帖子下方的评论功能......; - )
JQUERY:AJAX ....
var request = $.ajax({
url : "../command/test.php",
data : {"command": "apples"},
dataType : "json",
type : "POST"
});
request.done(function(data, textStatus, jqXHR){
if(data){
console.log(data);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
<强> PHP 强> ....
<?php
$response = array();
$command = isset($_POST['command']) ?
htmlspecialchars(trim($_POST['command'])) :
null;
if($command){
// BUILD UP YOUR RESPONSE HERE
$response['command'] = $command;
// ADD SOME ARBITRARY DATA - JUST FOR FUN
$response['name'] = "Albert";
$response['lastName'] = "Einstein";
}
die( json_encode($response) );
答案 3 :(得分:1)
你能试试吗
<script type="text/javascript">
$.ajax({
type: 'get',
url: "../command/test.php",
dataType: 'json',
data: ({command: 'apples'}),
success: function(data)
{
console.log("result: " + data);
}
});
</script>
答案 4 :(得分:1)
你需要发帖。您可以使用url args或传递数据对象。
$.ajax({
method: "POST",
url: "../command/test.php",
data: {
command: "apples"
}
})