簡體   English   中英

Ajax無法實現成功功能。 始終錯誤功能。 無法將數據發布到另一個文件

[英]Ajax doesn't get to success function. Always error function. It fails to post data to another file

請耐心等待。 據我所記得,這是我的第一篇文章。

這是我的calendar.js腳本的一部分。 我想POST ,我從模式窗口獲取數據index.phpsql.php

function saveModal() { /*JQuery*/
    var current_date_range = $(".modal-select#daterange").val();
    var current_room_number = $("#mod-current-room-number").val();
    var current_room_state = $("#mod-current-room-state").val();
    var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
    var myJSON = JSON.stringify(myData);

    $.ajax({
        type: "POST",
        url: "sql.php",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        data: myJSON,
        beforeSend: function() {
            $("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
        },
        success: function(result){
            $("#ajax").empty();
            $("#ajax").html(result);
            $("#ajax").fadeIn("slow");
            window.location.reload(true);
        },
        error: function(){
            alert(myJSON);
            $("#ajax").html("<p class='error'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Oops!</strong> Try that again in a few moments.</p>");
        }
    })    
}

我得到的數據就很好了(如您所見,我已經檢查了error: function() with alert(myJSON); )。 看起來像這樣: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"} 沒關系, daterangepicker.js以丑陋的MM/DD/YYYY格式返回日期,我非常想將其更改為YYYY-MM-DD 真正的問題是,代碼永遠不會success: function()

現在,我的sql.phpcalendar.jsindex.php位於同一文件夾中。

sql.php我嘗試使用以下方法檢索這些值:

$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);

我檢查了許多其他SO問答,但沒有一個可以幫助我解決問題。 我沒有看到任何拼寫錯誤。 這並不是違反same origin policy規則。 我不想使用jQuery $.post函數。 有人看到明顯的解決方案嗎?

您想發送數組而不是字符串,所以直接發送myData以獲取PHP文件中的數組值,而不是轉換為JSON字符串。它將根據需要與當前的PHP文件一起使用。

您應該為要發送的JSON數據字符串指定POST密鑰:

var myJSON = JSON.stringify(myData);
(...)
$.ajax({
    (...)
    data: 'data=' + myJSON,

您需要在PHP文件中解析(解碼)此字符串,然后才能再次將其用作數組/對象:

$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);

另外,jQuery.ajax函數中的dataType被指定為“期望從服務器返回的數據類型”。 根據jQuery文檔 據我從您的代碼中得知,您可能希望其他響應作為響應,因此請嘗試排除此行。

對不起,你們已經累了。 這是我的第三周編程,所以我缺乏知識是有錯的。 我不知道URL中AJAXPHP之間的數據流如何工作...

在搜索其他錯誤時,我打印或回顯了許多不同的內容。 盡管PHP文件可以是具有多個值的數組,但它僅應回顯1件事情。

例如:

$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);

我再次表示歉意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM