duanrong3308
duanrong3308
2016-05-01 18:21

如何使用jQuery合并两个json对象?

I have two json objects data and foo, i want to merge them and create a single json object. The resultant json should have all the values from foo and the values from data. so far i have something like this

javascript:

  $('#btn').click(function(){
            var imdbid=$('#tst').val();
            var url = "http://www.omdbapi.com/?i="+imdbid+"&plot=full&r=json"
            $.ajax({
            url:url,
            dataType:'json',
            success:function (json) {
                 data=json
                 var foo=$('form').serializeJSON() // store json string 
                 var marged=$.extend(data,foo);
                 console.log(marged);
                }
            })   
            }) 

HTML:

<form id="myform">
<label>imdb id:</label><input type="text"  id="tst" name="tst"/></form><br/>
<label>comment:-</label><input type="text" id="comment" name="comment" /><br/>
<label>link:-</label><input type="text" name="link" id="link" /><br/>
<input type="button" value="search"  id="btn"/>
</form>

the first object contains data returned from api and foo contains the values of form.i want to marge both object on a success function and send to php. when i am trying to print out the data it's as follows

{Title: "Mother's Day", Year: "2016", Rated: "PG-13", Released: "29 Apr 2016", Runtime: "118 min"…}
Actors
:
"Britt Robertson, Jennifer Aniston, Julia Roberts, Timothy Olyphant"
Awards
:

imdbID
:
"tt4824302"
tst
:
"tt4824302"

it's getting first input value not showing the second two.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudu7626 doudu7626 5年前

    You're closing the FORM on this line:

    <label>imdb id:</label><input type="text"  id="tst" name="tst"/></form><br/>
    

    ... so it only gets the first input field ; )

    点赞 评论 复制链接分享
  • drrog9853 drrog9853 5年前

    first change json to object than merge them as

    data=json
    
    var foo=$('form').serializeJSON();
    
    marged=$.extend(JSON.parse(data),JSON.parse(foo));
    
    console.log(marged);
    
    点赞 评论 复制链接分享