简体   繁体   中英

Ajax result always returns error even if function is successful

I have an Ajax function that looks like this

  $.ajax({
            type: "POST",
            url: "@IGT.baseUrl/SODetailsAjax/AddUnits",
            traditional: true,
            data: {
                __RequestVerificationToken: token,
                so_id: @Int32.Parse(Request["orderId"]),
                site_id: site,
                addItem_id: items,
                addItem_qty: itemsqty,
                addItem_disc: itemsdisc,
                addComp_id: comps,
                addComp_qty: compsqty,
                addComp_disc: compsdisc,
                addPart_id: parts,
                addPart_qty: partsqty,
                addPart_disc: partsdisc
            },
            success: function (data) {
             if(data.success === "False"){
                var errorMessage = data.Message;      
                alert("Error:" + errorMessage);
                return;
             }
             if(data.success === "True"){
                location.href = "../SalesOrders/Details?id=@so.ID";
             }            
            },
            error: function (jqXHR, status, error) {
                alert("Error:" + error);
            }
        });

And I have a JSON ActionResult method that does this in it.

  if (!canCreate)
                    {                 
                            var errorMessage = string.Join(",", errors);
                            var stock = new { success = "False", Message = errorMessage };
                            return Json(stock, JsonRequestBehavior.AllowGet);                                       
                    }
  else
                    {

                            var result = new { success = "True" };
                            return Json(result, JsonRequestBehavior.AllowGet);
                    }

But everytime Success is true it returns an error message saying "Error:Not defined" when I click "OK" it proceeds. But how can I make it so it just proceeds instead of sending an error message?

You have a couple of errors. In your if (data.Success = "false") statement, this is not a condition. This is an assignment. You should do if (data.success === "false") this would check for the condition. Also note that "success" is all lower case because it's converted to Json. You also need to note that "False" does not equal "false" so you must pick a casing. Either do "False"/"True" in both c# and JavaScript or "false"/"true".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM