[英]How to call included php file with AJAX?
我不确定这是否是最好的方法,但是如何使用包含的文件进行AJAX调用? 让我使工作简单的例子。
我有一个主要的index.php文件,具有以下内容,在这里我想访问发生魔术的包含文件返回的所有数据。 数据实际上是数组类型。
<?php
require_once('magic.php');
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
<input type="text" name="variable" id="variable" />
<input type="submit" value="Do magic" name="submit" />
</form>
<?php
echo "<pre>";
print_r($data);
echo "</pre>";
?>
</body>
</html>
还有“ magic.php”文件,其中发生了所有魔术。
<?php
$variable = $_POST['variable'];
function doMagic($variable) {
# do some magic with passed variable ...
# and return data
return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return $data;
?>
我想做的是用AJAX调用此函数doMagic(),但是所有逻辑都已包含在内并且可以在全局空间中使用,然后将$ data返回到模式窗口或弹出窗口。
最好的方法是什么,因为我已经将变量传递给包含的文件了?
像下面一样使用ajax
$('form').submit(function(){
$.ajax({url: "magic.php",
data: {variable : $'#variable').val()},
success:function(data){console.log(data);});
});
并在magic.php
中使用json_encode
<?php
$variable = $_POST['variable'];
function doMagic($variable) {
# do some magic with passed variable ...
# and return data
return $data;
}
$data = doMagic($variable);
# now return $data variable so main file can use it
return json_encode($data);
?>
由于您将jQuery
作为标签...
您可以执行以下操作:
在您的index.php中:
<input type="text" id="variable">
<div id="#myButton"></div>
<div id="#response"></div>
然后有一个Javascript文件(或包含在index.php中):
$('#myButton').click(function(){
var myVariable = $('#variable').val();
$.post( "magic.php",{variable: myVariable}, function(data) {
$( "#response" ).html( data );
});
});
这基本上意味着,当您单击ID为myButton
,它将获取ID为variable
ID的输入内容的variable
,并通过jQuery.post()将其POST到您的magic.php
文件中,并返回数据。 然后,它将返回的数据替换为带有response
ID的div的html。
只要确保包括jQuery库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.