使用AJAX和jQuery将JSON数据从一个页面发布到另一个页面

时间:2015-03-30 05:47:28

标签: php jquery json

我有

1。)textarea

2。)选择框

3。)按钮

我在textarea中传递JSON输入,并且点击按钮json数据被传递到另一个php页面“sendingInterface.php”,其中json数据通过函数传递到另一个名为“index.php”的页面,其中解码json和插入数据库。对此的反应是在另一个文本区域。

我的HTML代码:

<form id="data" action="" method="post" >

            <h3>Request</h3>
            <textarea name="jsondata" id="jsondata" value="">   </textarea>
            <br>
            <select name="listoptions" id="listoptions">
                <option selected="selected" value="">Select method</option>
                <option value="sendIncidentReport">sendIncidentReport</option>
                <option value="sendDeathReport">sendDeathReport</option>
</select>
            <br>
             <input type="button" name="send_report" id="send_report" value="Send Report">
             <br>
<h3>Response</h3>
         <br>
         <textarea name="response" id="response" rows="8" cols="8" value="">   </textarea>

<script>
    var url="http://localhost/API/sendingInterface.php?fn="
$(document).ready(function() {
        $("#send_report").click(function () {

        $.ajax({
        url:url + "sendIncidentReport", // calling url
        type: 'GET',
        data:{jsondata:$("#jsondata").val()         
        },
        cache: false,
        async: false,
        success: function(data) {
           $('#response').val(data);
        },
        error: function() {
        alert('Error');
        }
        });
});
}); 

$(document).ready(function() {
        $("#send_report").click(function () {

        $.ajax({
        url:url + "sendDeathReport", // calling url
        type: 'GET',
        data:{jsondata:$("#jsondata").val()         
        },
        cache: false,
        async: false,
        success: function(data) {
           $('#response').val(data);
        },
        error: function() {
        alert('Error');
        }
        });
});
});
</script>

PHP代码:sendingInterface.php

    <?php
    include_once 'index.php';
    $obj=new send();

    /*sendIncidentReport*/
    if($_GET['fn'] =="sendIncidentReport")
    {  
         $json=file_get_contents("php://input");
         $obj->sendIncidentReport($json);
        //$jsondata=$_GET['jsondata'];
        //$obj->sendIncidentReport($jsondata);
    }
    /*sendDeathReport*/
    if($_GET['fn'] =="sendDeathReport")
    {
          $json=file_get_contents("php://input");
          $obj->sendDeathReport($json);
        //$jsondata=$_GET['jsondata'];
        //$obj->sendDeathReport($jsondata);
    }
    ?>

我评论的PHP代码工作正常。但我想使用file_get_contents(“php:// input”)来获取json代码。

1 个答案:

答案 0 :(得分:0)

file_get_contents("php://input");将仅针对POST请求从请求正文中读取原始数据。 如果您计划将请求从GET更改为POST,那么您可以在jquery中使用以下代码来传递数据,以便在php://input流上提供。

$.ajax('url',{
'data': JSON.stringify(yourJSONObject), //{jsondata:$("#jsondata").val()}
'type': 'POST',
'processData': false,
});
相关问题