簡體   English   中英

在ajax查詢中將async屬性設置為false時,不會調用Web Api控制器

[英]Web Api conroller is not called when async property is set to false in ajax query

我有一個Web api控制器,該頁面由頁面上的ajax查詢調用。 當異步值設置為true時,一切正常。 當設置為false時,ajax查詢不會觸發。 見下面我的代碼

C#Web API控制器

using System;
using Microsoft.Xrm.Sdk;
using CRM_WebApp.Models;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.Xrm.Sdk.Query;
using CRM_WebApp.Services;
using System.Text.RegularExpressions;

namespace CRM_WebApp.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class CallBackFormController : ApiController
{
    [System.Web.Http.HttpPost]
    public System.Web.Http.IHttpActionResult Post([System.Web.Http.FromBody] CallBackFormModel CallBackFormModel)
    {
        ConnectiontoCrm connectiontoCrm = new ConnectiontoCrm();
        connectiontoCrm.GetConnectiontoCrmCopy();

        //Create Lead
        Entity lead = new Entity("lead");
        lead["firstname"] = CallBackFormModel.FirstName;

        return Json(new { result = "ok" });

    }
  }
}

下面是我的ajax查詢

<script>

$("input[name='crm']").click(function(){

   var Data = {FirstName : $("input[name='user_name']").val()};

   makeAjaxCall(Data);  

  });

function makeAjaxCall(Data){
    $.ajax({

                url: "http://localhost:54360///api/CallBackForm",
                type: "POST",
                dataType: "json",
                async: false,
                contentType: 'application/json',
                data: JSON.stringify(Data),

                success: function(data){

                    alert("DONESUCCESS"); 
                },
                error: function(data){
                    alert("DONEERROR");
                }
            });

     }

</script>

我不確定如何更改代碼以獲取錯誤

似乎工作正常,我使用了來自github Fake Online REST API

 (function CallTheServer() { $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", type: "POST", dataType: "json", async: false, /* change it to true or false see the effect of alert('Check me out too'), following the ajax*/ contentType: 'application/json', data: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }), success: function(data){ alert("DONESUCCESS " + JSON.stringify(data)); }, error: function(data){ alert("DONEERROR"); } }); alert('Check me out too'); })() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 

異步:錯誤不是一個好習慣。 設置async:false表示您正在使過程同步,因此瀏覽器將掛起它直到完成-無法繼續使用其他方法。 刪除該選項將使調用異步(默認情況下應該如此)。

如果您仍然想使用async:false,請閱讀鏈接-

http://api.jquery.com/jQuery.ajax/

暫無
暫無

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

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