繁体   English   中英

500内部服务器错误ajax / javascript

[英]500 internal server error ajax/javascript

我知道有一些关于此的帖子,但它们并没有帮助我。 我的程序正在运行,当我单击按钮触发javascript时,什么也没有发生,或者没有响应。 在网络标签下的Chrome调试器中,我看到红色

http://wms-wsdl.company.net/mobile.asmx/ContactGet?searchField=test&office=97&person=119&user=531&organization=14

当我单击该链接时,它显示一个带有500个内部服务器错误的红色圆圈。 如果单击响应,则会看到:

{"Message":"Invalid JSON primitive: test.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\\r\\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\\r\\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\\r\\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\\r\\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\\r\\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

现在我不知道那是什么意思。

当我双击该舔时,它显示了我所有应该插入列表视图的数据(数据为xml),例如<string xmlns="http://company.net/"> [ { "Name": "Myar", "Surname": "Tester", "Mobile": "080000000", "Email": "" ......}, etc

我的JavaScript函数如下:

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:successContact,
        failure: function (msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}


function successContact(data) {
    alert("Success Start Test");
    window.location = "#contactsview";
    $("#lstView_contacts").kendoMobileListView({
        dataSource: JSON.parse(data.d),
        template: $("#lstView_contact_Template").html(),
        endlessScroll: true,
        scrollThreshold: 8
    });
    alert("Success Start Test");    
}

searchTextField来自我的HTML文本框。

我似乎觉得奇怪的是,它获取了应该的数据,我已经在xml中进行了验证,但仍然给出错误。 我正在使用的Web服务是json Web服务。 它会同时发出警报,但我认为它会失败。

我在调试器中得到的响应是:

<string xmlns="http://company.net/">[
  {
    "Name": "Myar",
    "Surname": "Tester",
    "Mobile": "080000000",
    "Email": "test@test.com"
  }]</string

我的Web服务外观:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal searchField As String, ByVal office As String, ByVal person As String, ByVal user As String, ByVal organization As String) As String

        Dim objSearch As New ArrayList
        Dim objSearching As New Search
        Dim intResult As Integer

        Try
            'Test String
            intResult = objSearching.SearchByKeyword(searchField, person, office, organization, user, company.ETMyProperty.Search.enmSearchType.enmContact, objSearch)

            Dim objContact As New Person
            Dim dt As New DataTable("Contacts")

            Dim col_Name As New DataColumn("Name", GetType(String))
            dt.Columns.Add(col_Name)

            Dim col_Mobile As New DataColumn("Surname", GetType(String))
            dt.Columns.Add(col_Mobile)

            Dim col_Office As New DataColumn("Mobile", GetType(String))
            dt.Columns.Add(col_Office)

            Dim col_Category As New DataColumn("Email", GetType(String))
            dt.Columns.Add(col_Category)

            Dim dr As DataRow

            For i = 0 To objSearch.Count - 1
                dr = dt.NewRow()
                dr("Name") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return2
                dr("Surname") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return3
                dr("Mobile") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return6
                dr("Email") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return7
                dt.Rows.Add(dr)
            Next

            Dim serializer As New JavaScriptSerializer()
            Dim rows As New List(Of Dictionary(Of String, Object))()
            Dim row As Dictionary(Of String, Object) = Nothing

            'serialize dt row to json output
            For Each drow As DataRow In dt.Rows
                row = New Dictionary(Of String, Object)()
                For Each col As DataColumn In dt.Columns
                    row.Add(col.ColumnName, dr(col))
                Next
                rows.Add(row)
            Next

            Dim str_json = JsonConvert.SerializeObject(dt, Formatting.Indented)

            Return str_json

        Catch ex As Exception
            Return Nothing
        End Try
    End Function

我已经在这上待了几天,但我似乎找不到任何解决方案。 有什么帮助吗?

参考jQuery doc,您应该使用error: function() {...},而不是失败。 密钥成功的值应该是一个函数,而不是变量。 success: successContact(),东西success: successContact(),

为了以某种有用的方式进行调试,您需要知道ajaxcallback是调用成功还是错误。 如果没有成功,则可能是因为答案没有application / json内容类型标头,或者您的json错误。

因为您要处理GET请求,所以必须将contentType删除或定义为:

应用程序/ x-WWW窗体-urlencoded; 字符集= UTF-8

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:function (data) {successContact(data);},
        failure: function (msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}

还要检查错误是在ASMX上启动请求还是在ASMX响应上。

检查此详细信息获取请求: http获取请求是否需要内容类型?

还配置您的Web服务以返回JSON。 响应不是json。 因此,dataType现在不正确。 要仅重新运行json,请更改您的WebMethod。

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write("Hello World");
    //return "Hello World";
}

重要提示:如果您使用的是Web方法,则无需将数据表解析为json,则Webservice会为您完成。 因此,将其更改为:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal Parameters....) As DataTable

毕竟,这是一个适用于.net序列化的示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Collections;
using System.Linq;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public List<Dictionary<string, object>> HelloWorld()
    {
        DataTable TestTable = new DataTable();
        TestTable.Columns.Add("Name");
        TestTable.Columns.Add("Id");
        DataRow Row = TestTable.NewRow();
        Row["Name"] = "James";
        Row["Id"] = 0;
        TestTable.Rows.Add(Row);

        return RowsToDictionary(TestTable);
    }


    private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
    {
        List<Dictionary<string, object>> objs =
            new List<Dictionary<string, object>>();
        foreach (DataRow dr in table.Rows)
        {
            Dictionary<string, object> drow = new Dictionary<string, object>();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                drow.Add(table.Columns[i].ColumnName, dr[i]);
            }
            objs.Add(drow);
        }

        return objs;
    }

}

请检查其他序列化器,例如http://james.newtonking.com/json 也许可以使用比ASMX更好的ASHX处理程序来返回JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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