如何使用AJAX调用包含的php文件? [英] How to call included php file with AJAX?
问题描述
我不确定这是否是最好的方法,但是如何使用包含的文件进行AJAX调用?让我将工作示例简单化.
I am not sure if this is best approach, but how to make AJAX call with included file? Let me make working simple example.
我有一个主要的index.php文件,带有以下内容,我想在其中访问发生魔术的情况下从包含的文件返回的所有数据.数据实际上是数组类型.
I have, main index.php file, with following content, where I want to access all data returned from included file where magic happens. Data is array type in reality.
<?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"文件,其中发生了所有魔术.
And "magic.php" file, where all the magic happens.
<?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返回到模态或弹出窗口.
What I want to do is to call this function doMagic() with AJAX, but all logic is already included and available in global space, and return $data to modal or pop-up window.
什么是最好的方法,因为我已经将变量传递给包含的文件了?
What is best approach, because I am already passing variable to included file?
推荐答案
使用 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);
?>
这篇关于如何使用AJAX调用包含的php文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!