简体   繁体   English

如何在AJAX调用后通过Web API响应维护相同的JSON格式?

[英]How do I maintain the same JSON format from web API response after an AJAX call?

I have a web API that returns the following JSON: 我有一个Web API ,它返回以下JSON:

[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]

I want to pass JSON from the response to jqGrid to populate the data in a table, after my AJAX call which looks as follows: 我想将响应中的JSON传递给jqGrid,以在我的AJAX调用后填充表中的数据,如下所示:

function fetchMovies(){
    $.ajax({
        url: 'http://orionadmin.azurewebsites.net/api/movies',
        type: 'GET',
        datatype: 'JSON',
        contentType: 'application/json',
        success: function (data) {
            grid_data1 = JSON.stringify(data);
            alert(grid_data);
        },
        error: function (x, h, r) {
            alert('Something went wrong')
        }
    });
}

My result from the AJAX call looks as follows: 我从AJAX调用获得的结果如下所示:

"[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]"

This is the format jqGrid takes, to populate data in the table: 这是jqGrid用来填充表中数据的格式:

<script type="text/javascript">
    var grid_data = 
    [ 
        {id:"1",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"2",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"3",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"4",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"5",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
        {id:"6",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"7",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"8",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"9",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"10",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"11",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"12",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"13",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"14",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
        {id:"15",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"16",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"17",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"18",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"19",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"20",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"21",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"22",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"23",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}
    ];

How do I maintain the original JSON format without the " " after the AJAX call, so that I can get my data displayed in my jqGrid? 如何在AJAX调用后保持原始的JSON格式而没有" " ,以便可以将数据显示在jqGrid中?

也许是这样的吗?

'[{"MovieId":2,"Title":"End Game","Year"...'.replace(new RegExp('"', 'g'), '')

您不需要JSON.stringify(),您的数据已经是json格式

JSON is basically a format where you pass Javascript as a string. JSON基本上是一种将Javascript作为字符串传递的格式。 JQuery actually parses the string into an object, which is what you want. JQuery实际上将字符串解析为一个对象,这就是您想要的。 But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object. 但是,然后您将对象再次转换为JSON,这是一个字符串,但是您真正要使用的是对象。 TL;DR: Don't stringify it TL; DR:请勿将其归类

You can use addRowData method of JqGrid. 您可以使用JqGrid的addRowData方法。 it expects an object as input, since your result is an array of objects you just need to loop through the array and add Row Data 它期望一个对象作为输入,因为您的结果是一个对象数组,您只需要遍历该数组并添加行数据

 var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of US soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"},{"MovieId":4,"Title":"Cobra","Year":"1986","Actors":"Sylvester Stallone, Brigitte Nielsen, Reni Santoni, Andrew Robinson","Plot":"A tough-on-crime street cop must protect the only surviving witness to a strange murderous cult with far reaching plans","Director":"George P. Cosmatos","Cover":"cobra.jpg"},{"MovieId":5,"Title":"Savages","Year":"2012","Actors":"Blake Lively, Taylor Kitsch, Aaron Taylor-Johnson, Jana Banker","Plot":"Pot growers Ben and Chon face off against the Mexican drug cartel who kidnapped their shared girlfriend","Director":"Oliver Stone","Cover":"savages.jpg"},{"MovieId":6,"Title":"The Man in the Iron Mask","Year":"1998","Actors":"Leonardo DiCaprio, Jeremy Irons, John Malkovich, Gérard Depardieu","Plot":"The cruel King Louis XIV of France has a secret twin brother who he keeps imprisoned. Can the twin be substituted for the real king?\\"","Director":"Randall Wallac","Cover":"maninimask.jpg"},{"MovieId":7,"Title":"The Shawshank Redemption","Year":"1994","Actors":"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","Plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","Director":"Frank Darabont","Cover":"MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"},{"MovieId":8,"Title":"Perfume: The Story of a Murderer","Year":"2006","Actors":"Ben Whishaw, Francesc Albiol, Gonzalo Cunill, Roger Salvany","Plot":"Jean-Baptiste Grenouille, born with a superior olfactory sense, creates the world's finest perfume. His work, however, takes a dark turn as he searches for the ultimate scent.","Director":"Tom Tykwer","Cover":"MV5BMTI0NjUyMTk3Nl5BMl5BanBnXkFtZTcwOTA5MzkzMQ@@._V1_SX300.jpg"},{"MovieId":9,"Title":"Catch Me If You Can","Year":"2002","Actors":"Leonardo DiCaprio, Tom Hanks, Christopher Walken, Martin Sheen","Plot":"The true story of Frank Abagnale Jr. who, before his 19th birthday, successfully conned millions of dollars' worth of checks as a Pan Am pilot, doctor, and legal prosecutor.","Director":"Steven Spielberg","Cover":"MV5BMTY5MzYzNjc5NV5BMl5BanBnXkFtZTYwNTUyNTc2._V1_SX300.jpg"},{"MovieId":10,"Title":"James Bond 007","Year":"2003","Actors":"Pierce Brosnan, John Cleese, Willem Dafoe, Judi Dench","Plot":"MI6 agent James Bond:007 rushes into action to rescue Oxford scientist Katya Nadanova from a terrorist facility in Egypt. After rescuing Katya bond heads to a mining town in Peru to ..","Director":"Scot Bayless","Cover":"007.jpg"},{"MovieId":11,"Title":"The Mask","Year":"1994","Actors":"Jim Carrey, Peter Riegert, Peter Greene, Amy Yasbeck","Plot":"Bank clerk Stanley Ipkiss is transformed into a manic superhero when he wears a mysterious mas","Director":"Chuck Russel","Cover":"theMask.jpg"},{"MovieId":12,"Title":"Rambo","Year":"2008","Actors":"Sylvester Stallone, Julie Benz, Matthew Marsden, Graham McTavish","Plot":"In Thailand, John Rambo joins a group of missionaries to venture into war-torn Burma, and rescue a group of Christian aid workers who were kidnapped by the ruthless local infantry unit","Director":"Sylvester Stallone","Cover":"rambo.jpg"},{"MovieId":13,"Title":"The Green Mile","Year":"1999","Actors":"Tom Hanks, David Morse, Michael Clarke Duncan, Bonnie Hunt\\",\\"Plot\\":\\"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift","Plot":"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift.\\",\\"Language\\":\\"English, French\\",\\"Country\\":\\"USA\\",\\"Awards\\":\\"Nominated for 4 Oscars. Another 15 wins & 30 nominations","Director":"Frank Darabont","Cover":"greenmile.jpg"}] $("#grid").jqGrid({ datatype: "local", height: 250, colNames: ['MovieId', 'Title', 'Title', 'Actors', 'Plot','Director'], colModel: [{ name: 'MovieId', index: 'MovieId', width: 60, search:false}, { name: 'Title', index: 'Title', width: 120, search:false}, { name: 'Year', index: 'Year', width: 60, search:false}, { name: 'Actors', index: 'Actors', width: 120, search:false}, { name: 'Plot', index: 'Plot', width: 120, search:false}, { name: 'Director', index: 'Director', width: 120, search:false} ], caption: "IMDB" }); for (var i = 0; i <= data.length; i++) { $("#grid").jqGrid('addRowData', i + 1, data[i]); } 
 <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" rel="stylesheet"/> <link href="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/css/ui.jqgrid.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script> <table id="grid"></table> 

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

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