使用AJAX和JSON从服务器发送和接收信息

时间:2014-10-25 05:12:04

标签: javascript ajax json database server

我正在开发一个使用AJAX和JSON与服务器上的数据库进行交互的网页。

该页面应该向服务器发送两个信息(一个id号和一个事件),并返回一个与该ID号匹配的人的信息表({{1等)。我已经创建了表单并且它正确验证了,但是,我不知道从哪里开始。

我在过去的项目中涉足过AJAX,但却无法使用它,我从未使用过JSON(甚至不知道它是做什么的)。如果有人能帮助我,我们将不胜感激。

这是我到目前为止的代码:

fname, lname, sex,

提前致谢。

2 个答案:

答案 0 :(得分:2)

你必须更换' targetUrl'使用表单的动作网址。 (例如:' target.php')

<html>
<head>
<title>Project 6</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    function validate() {
        return checkEmpty();
    }

    function checkEmpty() {
        var ddl = document.getElementById("event");
        var ev = document.getElementById("id");
        var selectedEvent = ddl.options[ddl.selectedIndex].value;
        if(selectedEvent == "selectEvent" || id.value == "") {
            alert("Please enter an ID number or Event Type");
        }
    }

    $('document').ready(function(){
       $('#submit_btn').on('click',function(){
         $.post('targetUrl',$('#myform').serialize()).success(function(response){
            //code to handle response from server
         });
      });
    });
</script>
<style type="text/css">
    body {
        background-color: black;
        color: blue;
        text-align: center;
        border: 2px double blue;
    }
</style>
</head>

<body>
<h2>Welcome to our People Finder Database</h2>
Pleae fill out the following form to find information on the person you are looking for. <br>
While neither field is required, you must fill out at least one of the two fields to receive any information <br>
Also note that the ID number should be the letter "I" followed by a number. <br>
<form id="myform" onsubmit="return validate()">
    ID:<input type="text" id="id" name="id"> <br>
    Event Type:
        <select id="event" name="cards">
            <option value="selectEvent">Please select an event</option>
            <option value="BIRT">Birth</option>
            <option value="DEAT">Death</option>
            <option value="BURI">Buried</option>
        </select> <br>
    <input type="button" id="submit_btn" value="Submit"> <br>
</form>
</body>
</html>

答案 1 :(得分:1)

如果您不想存储和检索数据,我肯定会推荐https://parse.com/提供的服务。它使存储和检索数据变得微不足道。最重要的是,除非您的应用每秒发出超过30个API请求,否则该服务是免费的。我有一个61位用户每天使用的应用程序,我们从未接近每秒30 req的限制。

要保存您的信息,您可以写:

$('document').ready(function(){

    $('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button

        var EventInfo = Parse.Object.extend("EventInfo"); //create a reference to your class
        var newObject = new EventInfo(); //create a new instance of your class

        newObject.set("id", $("#id").val()); //set some properties on the object
        newObject.set("event", $("#event").val()); //set some more properties on the object
        newObject.save(null, { //save the new object
          success: function(returnedObject) {
            console.log('New object created with objectId: ' + returnedObject.id); 
          },
          error: function(returnedObject, error) {
            console.log('Failed to create new object, with error code: ' + error.message);
          }
        });
     });
});

稍后检索该信息将非常简单:

    var EventInfo = Parse.Object.extend("EventInfo"); //create a reference to your class
    var query = new Parse.Query(EventInfo); //create a query to get stored objects with this class
    query.find({
      success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific save objects too
        for (var i = 0; i < results.length; i++) { 
          var object = results[i];

          console.log("Result #"+ (i+1)); 
          console.log("Id = "+ object.get("id"));
          console.log("Event = "+ object.get("event"));
        }
      },
      error: function(error) {
        console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
      }
    });

如果你必须使用现有的数据库来存储信息,你可以将它发送到如下所示的php页面,但请注意,使用这种方法你仍然需要编写php页面来实际存储数据并在以后检索它,学习恕我直言的更多工作和更多东西。

$('document').ready(function(){
        $('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
           //get the inputted values 
            var dataString = 'id=' + $("#id").val()
                       + '&event=' + $("#event").val()
             //make the ajax call 
            $.ajax({
                type: "POST",
                url: "https://mywebsite.com/mypage.php",
                data: dataString,
                success: function(data) {
                  //do something with the returned data
                }
            });
        });
    });
相关问题