【发布时间】:2014-03-06 00:01:29
【问题描述】:
我正在使用 PHP 来处理来自表单的 AJAX POST 请求,并需要它来发回 JSON 对象。我的php代码。
<?php
function main(){
$a = $_POST['args'];
$myFile = "jsonargs.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fwrite($fh, "\n");
fwrite($fh, "-o ./json\n");
fwrite($fh, "-j\n");
fclose($fh);
$output = shell_exec('command 2>&1; ./syn-bin/synoptic-jar.sh -c jsonargs.txt ' . $_FILES["file"]["tmp_name"]);
$json = file_get_contents('./json.json');
header('Content-Type: application/json');
echo json_encode($json);
}
main();
?>
但是,当我使用 jquery 的 ajax 表单插件进行 ajax 调用时,会调用我的错误函数。如果我将其作为普通表单提交而不是进行 ajax 调用,则它可以正常工作。如何正确返回 JSON 对象?
我的 AJAX 请求:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
alert('About to submit: \n\n' + queryString);
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
console.log(responseText);
}
【问题讨论】:
-
StackOverflow 的语法高亮显示你显然在某处遇到了双引号问题...
-
是的,我在缩进代码时犯了一个错误。现在应该修好了。
-
也许检查控制台看看你从服务器得到什么错误?
-
Monkey 指出这一点:$_FILES["file" ["tmp_name"] - 应该是 $_FILES["file"]["tmp_name"]
-
@VolkanUlukut 小步,现在只是小步