簡體   English   中英

異步 jQuery ajax 方法始終將 null 數據發布到 API

[英]async jQuery ajax method always posting null data to API

我想在 JavaScript 中利用異步,但 function 不會將數據發布到 API(它始終是 null,無論是簡單變量還是對象)。 我已經在 Inte.net 上搜尋了幾個小時,並嘗試了我能想到的一切,驗證變量設置在 JavaScript 端並且總是調用 API,但是,該值是 null - 它正在發布,但從未真正發送數據。

這是 jQuery/JavaScript function。

async function RetrieveProfile(userId) {
    let result;
    try {
        result = await $.ajax({
            url: '../../api/GetProfile',
            dataType: 'json',
            method: 'post',
           data: { UserId: userId }
        });
        return result;
    } catch (e) {
        console.error(e);
    }
}

我試過設置數據:只是 userId,試過 stringify,試過刪除 dataType:'json',試過有和沒有 contentType,沒有快樂。 我知道 API 有效,因為我可以從 Postman 調用它並取回結果(盡管這是同步的)。

根據 Stack Overflow 上的每篇文章,這應該有效(我已經讓 async JavaScript 工作得很好,但他們總是發布到 ASMX 而不是 WebApi,所以必須為此做一些其他的改變正確發布)。

(注意:這不是 DotNet 核心。沒有中間件)。

[Route("api/GetProfile")]
[HttpPost]
public async Task<IHttpActionResult> GetProfile([FromBody] string UserId)
{
    var retval = new Profile();
    if (UserId != null)
    {
        if (await dbv.IsValidUserIdAsync(UserId))
        {
            retval = await profile_Data.GetProfileAsync(UserId);
        }
    }
    return Ok(retval);
}

我可以單步執行 JavaScript 並查看 userId 並將其設置為一個值(我什至在 try...catch 中設置了一個虛擬變量以驗證它仍然具有值。在 API 方面,UserId 是 null。我'我已經嘗試將其設置為 object - 仍然是 null。如果我刪除 [FromBody],我會收到 404 錯誤(並且未命中端點)。我相信,API 無法識別任何不是來自 HTML 的數據DOM - 忽略參數或 jQuery 3.1.1 中存在錯誤 - 我無法升級到 4.x 或 5.x 而不破壞其他地方的網站。

有任何想法嗎? 實際工作的例子? 我可以下載工作解決方案嗎? 我已經閱讀了手冊,但找不到具體的案例示例(jQuery 3.x + async + WebAPI 2.0 + non-DotNetCore)。

好的-我想通了。 我是正確的,因為 FromBody 只允許來自 HTML 主體的值(如其所說)。 因此 WebApi 忽略了數據(他們需要 [FromParam] 或類似的東西(MS 方面的疏忽)。

所以我在客戶端和 webapi 上將它從 POST 切換為 GET。

客戶端(JQuery/Javascript)端:

async function RetrieveProfile(userId) {
    let result;
    try {
        result = await $.ajax({
            url: '../../api/GetProfile',
            method: 'get',
           data: { UserId: userId }
        });
        return result;
    } catch (e) {
        console.error(e);
    }
}

在 webAPI 方面,我將代碼更改為:

    [Route("api/GetProfile")]
    [HttpGet]
    public async Task<IHttpActionResult> GetProfile([FromUri] string UserId)
    {
        var retval = new Profile();
        if (UserId != null)
        {
            if (await dbv.IsValidUserIdAsync(UserId))
            {
                retval = await profile_Data.GetProfileAsync(UserId);
            }
        }
        return Ok(retval);
    }

現在工作完美,但這只對 GET 有用,所以解決更新/插入對象的 POST 問題將是下一個問題(因為 FromBody 完全忽略發布的數據:如果使用異步 javascript - 噩夢繼續)

暫無
暫無

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

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