我有一个包含图层数组的编码对象,通过ajax调用发送到某个php文件,例如myfile.php。 php文件只是解码此对象并将图层名称推送到数据库中。现在我想在前端显示当前正在推送到数据库的layerName。
我的ajax请求如下:
$.ajax(
{
type: 'POST',
url: "funcs.php",
data:
{
targetAction : 'getProjectAssetId',
MetaData: allFiles,
},
success: function(data)
{
console.log("data: "+data);
},
//dataType: "json"
});
Funcs.php编码对象处理如下:
if(isset($_POST['MetaData']))
{
$project= explode("ProjectTag",$_POST['MetaData']);
echo "\nProject: ".$project[0]."\n";
$projectName=explode("Bounds: ",$project[0]);
$projectBounds=$projectName[1];
$projectName=explode("ProjectName:",$projectName[0]);
$projectName=$projectName[1];
echo "ProjectName: ".($projectName)."\n"."ProjectBounds: ".$projectBounds."\n";
$bound=json_decode($projectBounds,true);
// Hard coded groupID and no reference ID
$projectId= getProjectAssetId($projectName,25,'',$bound,''); // inserting Project Name in DB with hardcoded groupID and no reference
echo "\n ProjectId: ".$projectId."\n";
$files=explode(",oneFileTag,",$project[1]);
for($fileCounter=0;$fileCounter<count($files);$fileCounter++)
{
$message='Adding Layer: '.$files[$fileCounter];
echo'<scripttype="text/javascript">alert(\'asd\');notification("'.$message.'",2,"loading"); </script>';
$Layer=explode("LayerFieldTag",$desFileFields[0]);
$LayerName=explode("LayerName:",$Layer[0]);
$LayerName=$LayerName[1];
echo "\n\n\nLayerName: ".($LayerName)."\n";
$typeId= getLayerAssetType($LayerName,1);
$layerId=getLayerAssetId($LayerName,$projectId);
echo "\ntypeid: ".$typeId."\n";
echo "\nLayerid: ".$layerId."\n";
}
我想在for循环中执行javascript函数,我的意思是我想在用js文件编写的对话框中显示所有文件名。我面临的问题是它会被一个echo调用,但是这个echo会被ajax请求的成功函数捕获。我想执行这个echo命令。
答案 0 :(得分:1)
你的JS回调逻辑在错误的地方。通常,避免使用PHP编写Javascript逻辑。
相反,您应该从PHP文件返回一个JSON数组,然后将for循环移动到JS成功回调,并在那里循环执行JSON数组响应。
例如,像......
dataType: 'json',
success: function(files) {
for (var i in files) {
alert('asd');
notification('Adding Layer: ' + files[i], 2, 'loading');
}
}
基于查看您的JS和PHP,我强烈建议您花更多时间学习最佳实践和编码风格指南,然后再继续下去。花点时间和精力学习如何成为一名熟练的开发人员。