简体   繁体   English

服务器端的JSON字符串使用ajax jquery无法正常运行

[英]JSON string from server side not coming properly using ajax jquery

What I am doing is, i am getting data from server side using mvc . 我正在做的是,我使用mvc从服务器端获取数据。 The data is properly coming in return part. 数据正确地返回部分。 But when I m debugging in the client side, I am only getting the parameter value as [ . 但是当我在客户端进行调试时,我只将参数值设为[

Below is the JSON response which I am getting. 以下是我得到的JSON响应。

[{"VENDORNAME":"ABC","VENDORCODE":"1234"},{"VENDORNAME":"Abc test","VENDORCODE":"233311"},{"VENDORNAME":"ABC 2","VENDORCODE":"12345"}]

But when I check in the client I get it only [ in the parameter. 但是当我在客户端检查时,我只得到[在参数中。

Below is that code 以下是该代码

getValue: function (element) {        
        return {
            label: element.VENDORNAME,
            value: element.VENDORCODE
         };
    },  

in element i only get as [ element我只得到[

Please suggest where I am wrong 请告诉我错在哪里

update 更新

Here is the full code 这是完整的代码

var autocompleteOptions = {        

    url: function (phrase) {
        return AppConfig.PrefixURL + 'App/GetVendorData';
    },

    getValue: function () {        
        return {
            label: element.VENDORNAME,
            value: element.VENDORCODE
         };
    },      

    ajaxSettings: {
        dataType: "json",
        method: "POST",
        data: {
            dataType: "json",                
        }
    },        

    preparePostData: function (data) {
        data.phrase = $("#txtAssignVendor").val();           
        return data;
    },

    requestDelay: 400
};

And reference link below 以及下面的参考链接

http://easyautocomplete.com/examples#examples-ddg http://easyautocomplete.com/examples#examples-ddg

Server code 服务器代码

[HttpPost]
    public JsonResult GetVendorData(string phrase)
    {
        string strJsonData = "";
        try
        {
            Assignment ObjSAPAssign = new Assignment();
            DataTable dt = ObjSAPAssign.GetVendorList(phrase);               
            strJsonData = JsonConvert.SerializeObject(dt, Formatting.None);                
        }
        catch (Exception ex)
        {
            ApplicationLog.Error("Error", "GetVendorData", ex.Message);
            ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
        }
        return Json(strJsonData);
    }

Your server code: 你的服务器代码:

    string strJsonData = "";
    try
    {
        Assignment ObjSAPAssign = new Assignment();
        DataTable dt = ObjSAPAssign.GetVendorList(phrase);               
        strJsonData = JsonConvert.SerializeObject(dt, Formatting.None);                
    }
    catch (Exception ex)
    {
        ApplicationLog.Error("Error", "GetVendorData", ex.Message);
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
    }
    return Json(strJsonData);

You build the vendor list in dt , and then you use JsonConvert.SerializeObject() to build the response JSON. 您在dt构建供应商列表,然后使用JsonConvert.SerializeObject()来构建响应JSON。 However, you then serialize it again in that last call to Json() . 但是,然后在最后一次调用Json()再次序列化它。 It should be plain 应该很清楚

    return strJsonData;

That's why you get [ as the first "element": the autocomplete plugin is iterating through your JSON as a string . 这就是为什么你得到[作为第一个“元素”:自动完成插件以字符串形式迭代你的JSON。 If you change that return statement, it will properly receive your actual table. 如果更改了return语句,它将正确接收您的实际表。

edit — I'm pretty sure that the above describes the problem, but my suggestion won't work because that strJsonData is the wrong data type (not JsonResult ). 编辑 - 我很确定上面描述了这个问题,但是我的建议不起作用,因为strJsonData是错误的数据类型(而不是JsonResult )。 Based on this other question I think this might work: don't use JsonConvert.SerializeObject . 基于这个问题,我认为这可能JsonConvert.SerializeObject :不要使用JsonConvert.SerializeObject Instead, use plain Json() : 相反,使用普通的Json()

    DataTable dt;
    try
    {
        Assignment ObjSAPAssign = new Assignment();
        dt = ObjSAPAssign.GetVendorList(phrase);               

    }
    catch (Exception ex)
    {
        ApplicationLog.Error("Error", "GetVendorData", ex.Message);
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message);
    }
    return Json(dt, JsonRequestBehavior.AllowGet);                

(Note that I don't really know C# - the point is that you have to use Json() to get JsonResult from the DataTable .) (注意,我真的不知道C# - 关键是你必须使用Json()DataTable获取JsonResult 。)

Now once that's sorted out, and the autocomplete plugin is receiving the array properly, the next thing to decide is what to do with that getValue() function. 现在一旦整理完毕,自动完成插件正在正确接收数组,接下来要决定如何处理getValue()函数。 The plugin expects to be dealing with strings . 该插件希望处理字符串 In your code, you have that function return an object, and that's just going to confuse the plugin. 在你的代码中,你有该函数返回一个对象,这只会混淆插件。

I'm not sure what you need for the larger application, but the function could do something like this: 我不确定你需要更大的应用程序,但函数可以做这样的事情:

      getValue: function(element) {
        return element.VENDORNAME + " - " + element.VENDORCODE;
      }

The error was that you were serializing your DataTable twice, once by JsonConvert.SerializeObject() and the other by Json() method. 错误是您将DataTable序列化两次,一次是JsonConvert.SerializeObject() ,另一次是Json()方法。


Make a model class like this: 创建一个这样的模型类:

public class VendorData 
{ 
    public string VENDORNAME { get; set; } 
    public string VENDORCODE { get; set; } 
}

Here's the modified action method 这是修改后的操作方法

[HttpPost] 
public JsonResult GetVendorData(string phrase) 
{ 
    try 
    { 
        Assignment ObjSAPAssign = new Assignment(); 
        DataTable dt = ObjSAPAssign.GetVendorList(phrase); 
        List<VendorData> vendorList = dt.AsEnumerable().Select(row => new VendorData 
        { 
            VENDORNAME = row.Field<string>("VENDORNAME"), 
            VENDORCODE = row.Field<string>("VENDORCODE") 
        }).ToList();

        // Serializing only once 
        return Json(vendorList, JsonRequestBehavior.AllowGet); 
    } 
    catch (Exception ex) 
    { 
        ApplicationLog.Error("Error", "GetVendorData", ex.Message); 
        ErrorLog.HandleErrorLog("", "", "GetVendorData", ex.Message); 
        return Json(new object(), JsonRequestBehavior.AllowGet); 
    } 
}

and finally in the client side: 最后在客户端:

var autocompleteOptions = { 

url: function (phrase) { 
    return AppConfig.PrefixURL + 'App/GetVendorData'; 
}, 

getValue: "VENDORNAME", 

template: { 
    type: "description", 
    fields: { 
    description: "VENDORCODE" 
    } 
}, 

list: { 
    match: { 
        enabled: true 
    } 
}, 

ajaxSettings: { 
    dataType: "json", 
    method: "POST", 
    data: { 
        dataType: "json", 
    } 
}, 

preparePostData: function (data) { 
    data.phrase = $("#txtAssignVendor").val(); 
    return data; 
}, 

requestDelay: 400 
};

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

相关问题 如何读取来自jquery服务器端的XMLString - How to read XMLString coming from server side in jquery 使用ajax在服务器端恢复json时出错 - Error reciving json at server side using ajax jquery(服务器端)搜索和排序使用ajax - jquery (server side) search and sorting using ajax 使用 jQuery 对来自 Ajax 的 JSON 数据进行分组 - Use jQuery to group JSON data coming from Ajax 如何使用JQUERY使用AJAX将Javascript变量(从客户端)发布到PHP文件(服务器端) - How to POST a Javascript Variable (From Client Side) to PHP File (Server Side) with AJAX using JQUERY 来自服务器的延迟响应,同时中止jQuery Ajax - Coming late response from server while abort the jquery ajax 如何通过使用JSON,JQuery和AJAX从服务器获取数据? - How to get data from server by using JSON, JQuery and AJAX? 使用字符串从jQuery AJAX遍历JSON对象 - Traverse JSON object from jQuery AJAX using string 使用jQuery自动完成功能,我正在尝试在文本框中获取值,因为表中的数据不是来自使用文本字段中的ajax的json - using jquery autocomplete i am trying to get the value in the text box as table the datas are not coming from json using ajax in the text field 如何使用Jquery Ajax从服务器端在客户端页面中打印成功消息 - How to print success message in the client page from the server side using Jquery Ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM