500内部服务器错误ajax / javascript

时间:2014-04-10 10:16:37

标签: javascript ajax json

我知道有一些帖子,但他们没有帮助我。 我的程序运行了,当我点击按钮触发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 webservice。 它会警告两个警报,但我认为它会失败。

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

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

我的网络服务看起来如何:

<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

我已经在这几天了,我似乎无法得到任何解决方案。 有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

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

这样的东西

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

答案 1 :(得分:0)

因为您正在发送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响应上的错误时是否出现错误。

检查此详细信息获取请求: Do I need a content type for http get requests?

还配置您的webservice以返回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";
}

重要提示:如果您使用的是webmethods,则不需要将数据表解析为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。也许您可以使用ASHX处理程序而不是ASMX来返回JSON。