Ajax call returns 200 OK 但没有调用 web 方法

Ajax call returns 200 OK but not calling the web method

我有 ajax 调用如下

$.ajax({
  type: "POST",
  url: "MainPortal/VirtualRoomService.asmx/SaveJunit",
  data: JSON.stringify({
    xjunit: junit,
    data: editor.getData().trim()
  }),
  contentType: "application/json; charset=utf-8",
  async: false,
  dataType: "json",
  success: function(result) {
    if (result.d.split('|')[0] != "-1") {
      $("#<%=lblMessage.ClientID%>").text("Junit saved successfully");
    } else {
      $("#<%=lblMessage.ClientID%>").text(result.d.split('|')[1]);
    }
  },
  error: function(result) {
    if (result.status == 200 && result.statusText == 'OK') {} else {
      alert("FAILED : " + result.status + ' ' + result.statusText);
    }
  }

});

下面是 .asmx 网络服务中定义的 SaveJunit 代码

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SaveJunit(string xjunit, string data)
{
    try
    {
        #region JunitInformation
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xjunit);
        XmlElement xRoot = doc.DocumentElement;
        XmlNode xmlJunit = xRoot.SelectSingleNode("/junit");
        XmlNode xType = xRoot.SelectSingleNode("/junit/type");
        XmlNode xInfo = xRoot.SelectSingleNode("/junit/info");

        MJunitList mJunitList = MJunitList.GetNewInstance;
        mJunitList.JunitTypeId = Convert.ToInt32(xType["id"].InnerText);
        mJunitList.JunitLabelId = Convert.ToInt32(xmlJunit["label"].InnerText);
        mJunitList.Deck = xmlJunit["deck"].InnerText;
        mJunitList.HasGalleryList = false;
        mJunitList.IntroText = xmlJunit["intro"].InnerText;
        if (string.IsNullOrEmpty(xmlJunit["status"].InnerText))
        {
            mJunitList.JunitStatusId = (int)JunitStatus.New;
        }
        else
        {
            mJunitList.JunitStatusId = Convert.ToInt32(xmlJunit["status"].InnerText, CultureInfo.CurrentCulture);
        }
        mJunitList.JunitSlug =
            CommonUtility.EncodeChar(xmlJunit["slug"].InnerText);
        if(!string.IsNullOrEmpty(xmlJunit["byline"].InnerText))
        {
            MInternalUser mInternalUser = MInternalUser.GetNewInstance;
            mInternalUser.PublicationIds = xmlJunit["publication"].InnerText;
            Collection<MInternalUser> objUsers =
                BllInternalUser.GetActiveInternalUserByPublicationId(mInternalUser, GeneralMethods.IsServiceRequired()).InternalUsers;
            var objByLine = new Collection<MByLine>();

            string[] juniByline = xmlJunit["byline"].InnerText.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < juniByline.Length; i++)
            {
                MByLine mByLine = MByLine.GetNewInstance;
                mByLine.Byline = juniByline[i];
                mByLine.UserId = objUsers.Where(n => n.ByLineName.ToLower().Equals(juniByline[i].ToLower())).First().InternalUserId;
                objByLine.Add(mByLine);
            }
            mJunitList.Bylines = objByLine;
        }

        if(!string.IsNullOrEmpty(xInfo["infodate"].InnerText))
            mJunitList.InfoBoxDate = CommonUtility.EncodeChar(xInfo["infodate"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infotime"].InnerText))
            mJunitList.InfoBoxTime = CommonUtility.EncodeChar(xInfo["infotime"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infoloc"].InnerText))
            mJunitList.InfoBoxLocation = CommonUtility.EncodeChar(xInfo["infoloc"].InnerText);
        if(!string.IsNullOrEmpty(xInfo["infotext"].InnerText))
            mJunitList.InfoBoxText = CommonUtility.EncodeChar(xInfo["infotext"].InnerText.Trim());

        #endregion

        if (string.IsNullOrEmpty(xmlJunit["id"].InnerText))
        {
            mJunitList.CapsuleId = int.Parse(xmlJunit["capid"].InnerText);
            mJunitList.PublicationIds = xmlJunit["publication"].InnerText;
            mJunitList.CreatedBy = Convert.ToInt32(xmlJunit["createdby"].InnerText);
            if (!string.IsNullOrEmpty(xmlJunit["tags"].InnerText.Trim()))
            {
                mJunitList.Tags = xmlJunit["tags"].InnerText.Trim().Trim(',');
            }
            mJunitList = BllJunitList.UpdateJunitList(mJunitList, Statement.Insert, GeneralMethods.IsServiceRequired());

            if (mJunitList.JunitId > 0)
            {
     //           return mJunitList.JunitId.ToString();
            }

            if (mJunitList.EffectedRows == (int)QueryStatus.Duplicate)
            {
                return string.Format("-1|Error duplicate record");
            }
            else
            {
                return string.Format("-1|Error transaction failed");
            }
        }
        else
        {
            //if (imbSave.Visible)
            //{
                mJunitList.JunitId = Convert.ToInt32(xmlJunit["id"].InnerText, CultureInfo.CurrentCulture);
                mJunitList.PublicationIds = xmlJunit["publication"].InnerText;
                mJunitList.UpdatedBy = Convert.ToInt32(xmlJunit["createdby"].InnerText);
                #region Tag Information

                //mJunitList.DeleteTags = DeleteJunitTags();
                //mJunitList.JunitTags = InsertJunitTags();
                if (!string.IsNullOrEmpty(xmlJunit["tags"].InnerText.Trim()))
                {
                    mJunitList.Tags = xmlJunit["tags"].InnerText.Trim().Trim(',');
                }

                #endregion

                int effectedRows =
                    BllJunitList.UpdateJunitList(mJunitList, Statement.Update, GeneralMethods.IsServiceRequired()).EffectedRows;
                if (effectedRows == (int)QueryStatus.Success)
                {
                    //                            return mJunitList.JunitId.ToString();
                }
                else
                {
                    return string.Format("-1|Error transaction failed");
                }
            //}
        }

        string path = Path.Combine(Server.MapPath(ApplicationConstants.CONTENTLIBRARY_VARIABLE),
                                     xmlJunit["publication"].InnerText);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        string fullpath = Path.Combine(path, mJunitList.JunitId.ToString());
        Directory.CreateDirectory(fullpath);
        if (data.Length > 0)
        {
            string htmlfile = string.Format("{0}\{1}.html", fullpath, DateTime.Now.ToString("MMddyyHHmmss"));

            // var ajxFileUpload = htmlEditorExtender.AjaxFileUpload;
            // ajxFileUpload.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}/{3}.html", ApplicationConstants.COMMONLIBRARY_VARIABLE, hdnPublicationId.Value, hdnJunitId.Value, DateTime.Now.ToString("MMddyy"))));
            using (FileStream fS = new FileStream(htmlfile, FileMode.Create))
            {
                using (StreamWriter fStrm = new StreamWriter(fS, Encoding.UTF8))
                {
                    fStrm.Write(HttpUtility.HtmlDecode(data));
                    //fStrm.Write(htmlEditorTextBox.Text.Replace("&lt;", "<").Replace("&gt;", ">"));
                    fStrm.Close();
                }
                fS.Close();
            }
        }
        var directory = new DirectoryInfo(path);
        if (directory.GetFiles().Count() > 0)
        {
            var files = (from f in directory.GetFiles()
                         orderby f.LastWriteTime descending
                         select f).ToList();
            if (files != null)
            {
                for (int i = 0; i < files.Count(); i++)
                {
                    files[i].MoveTo(string.Format("{0}\{1}", fullpath, files[i].Name));
                }
            }
        }
        return mJunitList.JunitId.ToString();
    }
    catch (Exception eX)
    {
        return string.Format("-1|{0}", eX.Message);
    }
}

ajax 总是调用 returns 200 OK 但函数从未被调用 下面是从客户端调试器 (chrome)

捕获的请求数据
 {"xjunit":"<?xml version=\"1.0\" encoding=\"utf-8\"?><junit><byline>Mohan</byline><id></id><capid>102</capid><status></status><slug> 17</slug><tags>tags</tags><publication>21</publication><type><id>17</id><name>Text</name></type><label>21</label><deck>deck1</deck><intro>intro</intro><info><infodate></infodate><infotime></infotime><infoloc>loc</infoloc><infotext>info</infotext></info><createdby>7</createdby></junit>","data":"<p>content</p>"}

更新

我变了

error: function(result) {

error: function (jqXHR, textStatus, errorThrown) {

了解错误。 textStatus 显示为 parsererror 并且在 errorThrown 中显示意外的输入结束

更改此行:

data: JSON.stringify({xjunit: junit, data: editor.getData().trim()}),

至:

data: {xjunit: junit, data: editor.getData().trim()},

实际上 URL

MainPortal/VirtualRoomService.asmx 

没有指向正确的位置。这是主要问题。将 URL 指向正确的位置已经解决了这个问题不知道为什么响应是 200 OK 对于一个坏的 URL?希望这个回答能对遇到类似问题的人有所帮助。