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

时间:2022-10-30 23:28:05

I have a web API that returns the following JSON:

我有一个返回以下JSON的web API:

[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick F*","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:

在我的AJAX调用之后,我想将JSON从响应传递到jqGrid,以填充表中的数据,调用如下所示:

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 F*","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中显示数据?

4 个解决方案

#1


1  

Maybe something like this?

也许是这样的?

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

#2


1  

You don't need JSON.stringify(), your data is already in json format

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

#3


0  

JSON is basically a format where you pass Javascript as a string. JQuery actually parses the string into an object, which is what you want. But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object. TL;DR: Don't stringify it

JSON基本上是一种将Javascript作为字符串传递的格式。JQuery实际上将字符串解析为一个对象,这是您想要的。然后再将对象转换为JSON,这是一个字符串,但真正需要使用的是对象。TL;函数博士:别把它

#4


0  

You can use addRowData method of JqGrid. 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

可以使用JqGrid的addRowData方法。它需要一个对象作为输入,因为您的结果是一个对象数组,您只需要在数组中循环并添加行数据

var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick F*","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"},{"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 im*ed. 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 im*ed 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>

#1


1  

Maybe something like this?

也许是这样的?

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

#2


1  

You don't need JSON.stringify(), your data is already in json format

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

#3


0  

JSON is basically a format where you pass Javascript as a string. JQuery actually parses the string into an object, which is what you want. But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object. TL;DR: Don't stringify it

JSON基本上是一种将Javascript作为字符串传递的格式。JQuery实际上将字符串解析为一个对象,这是您想要的。然后再将对象转换为JSON,这是一个字符串,但真正需要使用的是对象。TL;函数博士:别把它

#4


0  

You can use addRowData method of JqGrid. 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

可以使用JqGrid的addRowData方法。它需要一个对象作为输入,因为您的结果是一个对象数组,您只需要在数组中循环并添加行数据

var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick F*","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"},{"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 im*ed. 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 im*ed 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>