AJAX调用未按预期工作

Azi*_*ima 5 php ajax jquery

我正在尝试使用ajax发送表单数据.但是ajax操作中存在错误,只执行"错误"回调函数.这是我试过的:

$("#issue_submit").click(function (e) {

    console.log("clicked on the issue submit");
    e.preventDefault();

    // Validate the form
    var procurementForm = $("#it_procuremet_form");

    if($(procurementForm).valid()===false){
        return false;
    }

    // Show ajax loader
    appendData();

    var formData = $(procurementForm).serialize();

    // Send request to save the records through ajax
    var formRequest = $.ajax({
        url: app.baseurl("itprocurement/save"),
        data: formData,
        type: "POST",
        dataType: "json"
    });

    formRequest.done(function (res) {
        console.log(res);
    });


    formRequest.error(function (res, err) {
        console.log(res);
    });


    formRequest.always(function () {
        $("#overlay-procurement").remove();
        // do somethings that always needs to occur regardless of error or success
    });

});
Run Code Online (Sandbox Code Playgroud)

路由定义为:

$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Run Code Online (Sandbox Code Playgroud)

我还补充说:

$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
Run Code Online (Sandbox Code Playgroud)

我尝试将一个简单的字符串返回到控制器类的ajax调用. ITProcurementController.php:

public function save($f3)
{
    echo 'Problem!';
    return;
    $post = $f3->get('POST');
}
Run Code Online (Sandbox Code Playgroud)

但只执行'错误'回调.我找不到有什么问题.请帮忙.

jer*_*oen 5

你指定你期望json回来:

// Send request to save the records through ajax
var formRequest = $.ajax({
    url: app.baseurl("itprocurement/save"),
    data: formData,
    type: "POST",
    // Here you specify that you expect json back:
    dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)

你发回的不是json:

echo 'Problem!';
return;
Run Code Online (Sandbox Code Playgroud)

这是一个不带引号的字符串,它不是有效的json.

要发回有效的json,您需要:

echo json_encode('Problem!');
return;
Run Code Online (Sandbox Code Playgroud)

您也可以dataType根据需要删除该属性.