如何从php中的查询传递数据并使用ajax方法设置其结果。 以下是我目前在名为file1.php的文件中的内容:
import glob
from PIL import Image
for infile in glob.glob("/Gallery/**/*.jpg", recursive=True):
basewidth = 800
img = Image.open(infile)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save(infile)
我想将这些内容放在php文件file2.php中的这个html元素中:
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
很多筹码溢出的帖子都没有任何帮助。有人能指出我正确的方向吗?
答案 0 :(得分:0)
这是错误的做法。
您应该创建一个php脚本,它会将您的ajax请求数据保存在数据库中,然后在file2.php
中从DB加载此数据,不直接更新文件
答案 1 :(得分:0)
首先,query.php返回什么样的内容?它是一个JSON对象还是你只是回应&#34;输出为字符串?
下一个问题:您是否正在使用jQuery,AngularJS或其他方向?
通常你想要做的是从&#34; query.php&#34;获取信息。并将其作为JSON格式的ajax结果传递...
现在你的实际问题:你想得到名为&#34; resultFromFile1&#34;那个在file2.php里面但是你没有向&#34;可见范围&#34;添加任何内容。但由于Load仅加载内容,但它不会将内容添加到您必须定义包含&#34; file2.php&#34;的元素的任何元素。如果我是你要避免所有这些问题,我会使用AngularJS将你的数据显示到一个视图中,然后只包括你的&#34;结果&#34;通过ng-include模板,让ajax填充文档..
解决问题:
<script type = "text/javascript">
// Your Solution
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
// My Solution for this problem using native js
// Load the "file2" contents in to the file2Holder element
LoadUrlToElement('file2.php','file2Holder',function(data){
/* When the first loading of file2.php is done, load the results from the query.php and put it in to the element called "resultFromFile1" which we just loaded and placed in to the dom before. But i would recommend you to use AngularJS to avoid this Callback hell and get many cool features that webdevelopers don't want to miss these days.... */
LoadUrlToElement('query.php','resultFromFile1',function(){
alert('Content of resultFromFile1 is => '+document.getElementById('resultFromFile1'));
});
});
function LoadUrlToElement(url,elementID,done) {
$.ajax( { type : 'POST',
data : { },
url : url,
success: function ( data ) {
if(document.getElementById(elementID) === undefined){
alert("Can't proceed cause the content holder"+elementID+" is not found");
return; // Abort here cause there is no container with this id...
}
document.getElementById(elementID).html = data;
if(done !== undefined && typeof done === 'function') done(data);
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<div id="file2Holder"></div>