如何将提取的Json数据导入数据库

时间:2016-04-28 02:27:42

标签: php jquery html sql json

我正在尝试从omdbapi获取电影信息。所以我有这个代码,它使用omdb api从imdb中提取数据。但我想将数据导入我的数据库。我是否实现了这一点。

我的代码看起来像这样

    <form>
<input type="text"  id="tst"/>
<input type="button" value="search"  id="btn"/>
</form>
<table class="table table-hover" id="imdb">
        <thead>
            <tr>
                <th>Poster</th>
                <th>Title</th>
                <th>Year</th>
                <th>Rated</th>
                <th>Runtime</th>
                <th>Genre</th>
                <th>Director</th>
                <th>Actors</th>
                <th>Plot</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

这是我用来获取电影信息的jquery代码

$(document).ready(function () {
          $('#btn').click(function(){
              var imdbid=$('#tst').val();
               var url = "http://www.omdbapi.com/?i="+imdbid+"&plot=short&r=json"
        $.ajax({
        url:url,
        dataType:'json',
        success:function (json) {
            var tr;
        tr = $('<tr/>');
        tr.append("<td><img src=" + json.Poster + " width='200' height='297'></td>");
        tr.append("<td>" + json.Title + "</td>");
        tr.append("<td>" + json.Year + "</td>");
        tr.append("<td>" + json.Rated + "</td>");
        tr.append("<td>" + json.Runtime + "</td>");
        tr.append("<td>" + json.Genre + "</td>");
        tr.append("<td>" + json.Director + "</td>");
        tr.append("<td>" + json.Actors + "</td>");
        tr.append("<td>" + json.Plot + "</td>");
        $('#imdb').append(tr);
        }
        })
              })
    });

1 个答案:

答案 0 :(得分:0)

您可以从api响应中创建一个json对象(在您创建html的同一个函数中)。

 JSONData = JSON.stringify({
            "Title": Title,
            "Year": Year,
            "Rated" : Rated,
            ...........so on

        });
postDataToserver(JSONData);

您可以定义函数来发布数据,如 -

function postDataToserver(JSONData)
    $.ajax({
        url: "your_server_script_path",
        type:"POST",
        data:JSONData,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
        error: function (error) {

        }
    });

如果您想要发送简单的帖子格式而不是JSON对象,那么您不需要使用JSON.stringify,并且类似地在函数中删除内容类型信息。希望这会对你有所帮助。