ajax请求无法与php通信

时间:2016-07-29 18:14:02

标签: javascript php html ajax

后台:我有一个包含一些JavaScript的HTML文件。此文件托管在服务器上。在同一目录中,有一个PHP文件。记住这一点。

用户选择一些选项,站点会根据这些选项生成XML字符串。然后,我想将此XML字符串传递给PHP文件以生成XML文件,并在此服务器上执行有关此文件的命令。

问题:尝试AJAX GET请求时收到错误400(错误请求)。为什么?是因为文件在同一个目录中吗?

JS AJAX:

        $.ajax({
        type: "GET",
        url: 'Submit_Job_to__Computer_Cluster.php',
        data: {XML_requested_job :  XML_string},
        dataType: "json",
        success: function (msg) {
           console.log(msg);
        },
        error: function (errormessage) {
            console.log("error: " + errormessage);
        }
    });

PHP:

<?php
header("Access-Control-Allow-Origin: *");
$today = getdate();
$year = (string) $today['year'];
$month = (string) $today['month'];
$day = (string) $today['mday'];
$XML_string = $_GET["XML_requested_job"]; //here's where the query data comes into play
$db_path = " /tmp/";
$db_path .= $year;
$db_path .= $month;
$db_path .= $day;
$db_path .= ".db";
$rocoto_path = "/work/apps/gnu_4.8.5/rocoto/1.2.1/bin/rocotorun";   
$XML_file= "workflowPROD.xml";
$file_handle = fopen($XML_file, 'w') or die("Can't open the file");
fwrite($file_handle, $XML_string);
fclose($file_handle);
//concatenate command
$exec_command = $rocoto_path;
$exec_command .= " -w ";
$exec_command .= $XML_file;
$exec_command .= " -d";
$exec_command .= $db_path;
echo json_encode($XML_string);
shell_exec($exec_command);?>

编辑:将类型更改为POST会引发501未实现的错误。

2 个答案:

答案 0 :(得分:2)

最可能的原因是你说:

contentType: "text/html; charset=utf-8",

此内容类型会触发preflight OPTIONS request,因为它不在安全内容类型列表中(即您可以使用纯HTML格式触发的内容类型)。

您可以使用浏览器的开发者工具的“网络”标签检查是否属于这种情况。

如果服务器没有正确配置,它可以响应带有400 Bad Request错误的OPTIONS请求。

要解决此问题,请删除该行。由于您没有在请求正文中发布,发布或以其他方式发送HTML文档,因此无论如何都是谎言。

答案 1 :(得分:0)

找到了问题并解决了它。

事实证明我必须对传递的数据进行编码,菜鸟错误。

  1. 制作变量:var encodedXML = encodeURI(XML_String);
  2. 改为引用该变量(encodedXML):data: {XML_requested_job : encodedXML}
  3. 感谢所有的评论和帮助。