如何使用XMLHTTP将变量从JavaScript传递到PHP页面

时间:2015-03-31 17:14:52

标签: javascript php jquery html ajax

请在将说明标记为重复之前阅读说明。

据我所知,将数据从JavaScript传递到PHP的方法是通过Ajax Call。

我的情况是这样的:

  1. 使用PHP,我回显一个包含JavaScript的HTML页面。

    <?php        
    $out .= '    
    <h3>Upload New Primary Studies</h3>    
    <div>    
    <p> Please select the primary studies which you want to upload:</p>    
    <table>    
    <form id="file-form" action="" method="POST">
    <Tr><input type="file" id="file-select" name="userFile" multiple/>                 
    <button type="submit" id="upload-button"">Upload</button>                 
    </Tr>               
    </form>      
    </table>        
    </div>
    
    <h3>View / Edit Primary Studies</h3>
    <div id="grid1"></div>
    <script>
    
    var form = document.getElementById("file-form");
    var fileSelect = document.getElementById("file-select");
    var uploadButton = document.getElementById("upload-button");
    var today = new Date();
    var idValue = 1;      
    var jsonData = {
    
        header: []
    
    };
    
    var data1;
    
    form.onsubmit = function(event) {
      event.preventDefault();
    
    // Update button text.
    uploadButton.innerHTML = "Uploading...";
    
    
    // Get the selected files from the input.
    var files = fileSelect.files;
    var file1 = files[0];
    
    var i = 1;
    var reader = new FileReader();
    reader.readAsText(file1);
    reader.onload = function(event){
        var csv = event.target.result;
        var data = $.csv.toArrays(csv);
        for(var row in data) {
            if ( row == 0)
                continue;
            else
            {
                jsonData.header.push({
    
                    "ID" : idValue,
                    "RefID" : 1,
                    "RefType" : data[row][0],
                    "recordDate" : new Date().toJSON().slice(0,10),
                    "PrimaryAuthors" : data[row][1],
                    "PrimaryTitle" : data[row][2],
                    "FullPeriodical" : data[row][3],
                    "PeriodicalAbbrev" : data[row][4],
                    "PubYear" : data[row][5],
                    "PubDate" : data[row][6],
                    "Volume" : data[row][7],
                    "Issue" : data[row][8],
                    "StartPage" : data[row][9],
                    "OtherPage" : data[row][10],
                    "Keywords" : data[row][11],
                    "Abstract" : data[row][12],
                    "Notes" : data[row][13],
                    "PersonalNotes" : data[row][14],
                    "SecondaryAuthors" : data[row][15],
                    "SecondaryTitle" : data[row][16],
                    "Edition" : data[row][17],
                    "Publisher" : data[row][18],
                    "PlacePub" : data[row][19],
                    "TertiaryAuthors" : data[row][20],
                    "QuaternaryAuthors" : data[row][21],
                    "QuinaryAuthors" : data[row][22],
                    "TertiaryTitle" : data[row][23],
                    "ISSN" : data[row][24],
                    "Availability" : data[row][25],
                    "Address" : data[row][26],
                    "AccNumber" : data[row][27],
                    "Language" : data[row][28],
                    "Classification" : data[row][29],
                    "SubFile" : data[row][30],
                    "OrgForiegnTitle" : data[row][31],
                    "url" : data[row][32],
                    "DOI" : data[row][33],
                    "CallNumber" : data[row][34],
                    "Database" : data[row][35],
                    "DataSource" : data[row][36],
                    "IdentPhrase" : data[row][37],
                    "RetDate" : data[row][38]
                });
                idValue++;
            }
        }
            data1 = jsonData;
            //alert(JSON.stringify(data1));
            $("#grid1").igGrid("dataSourceObject", data1);
            $("#grid1").igGrid("dataBind");
    
        }
    
    
        uploadButton.innerHTML = "Upload Complete";
    }
    
    // Call the grid with JSON Data
    $( document ).ready(grid1());
    var request;
    function createDBRows()
    {
        var r = confirm("Do you want to create records in the database");
    
        var url = "/_application/model/dataAccess/insertStudies.php?json=";
        if (r == true) {
    
            alert("You pressed OK!");
            // Get the database of the Grid
            var dbSource = $("#grid1").igGrid().data().igGrid.dataSourceObject();
    
    
    
        } else {
           alert("You pressed Cancel!");
        }
    }
    </script>
    <br>
    <br>
    
    <div>
    
    <button type="submit" id="upload-button"" onclick="createDBRows()">Create  Database Rows</button>
    
    <button type="clear" id="clear-button"">Clear</button>    
    <button type="cancel" id="cancel-button"">Cancel</button>
    </div>
    ';
    
  2. 此应用程序的步骤如下:

    1. 上传CSV文件。
    2. CSV文件中的数据显示在iggrid中。
    3. 用户修改数据&amp;将其保存在网格上。
    4. 用户完成修改后,用户点击“创建数据库行”按钮
    5. 点击上面的按钮,数据源应传递到另一个PHP页面:insertStudies.php
  3. 我的问题:

    我被困在第2.e点,因为我无法创建ajax调用并将数据发送到php页面。任何人都可以指向一个源或给出一个示例,它可以解释使用带有PHP页面的javascript将数据传递到另一个PHP页面的方法。

2 个答案:

答案 0 :(得分:0)

您要求的是Ajax Post method

您可以通过json数组或序列化形式将数据发送到php页面。

该函数将php页面中的“echoed”数据返回到带有结果类

的标记中
$.post("path/yourPhpPage.php",{key: 'value'}, function( data ) {
  $( ".result" ).html( data );
});

答案 1 :(得分:0)

点击按钮会运行 SCRIPT (进一步将3个JS变量传递给 abc.php

<script type="text/javascript">
    function sendJSValsToPHP(){
        var xmlhttp;

        //These are the variables i am going to post to illustrate the example, what you want
        var var_1toPost = 1;
        var var_2toPost = 2;
        var var_3toPost = 3;

        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                //You can get the response text from abc.php file and process it in any of the tags you want by javascript code
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;              
            }
        }
        xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
        xmlhttp.send();
    }
</script>

abc.php中的回声数据将出现在div="myDiv" //as a response.

<body>
    <div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
        the things echo'ed in abc.php will come in this div
    </div>
    <button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>

然后在 abc.php //文件

<?php
    $recieved_1 = $_GET['recieve_1'];
    $recieved_2 = $_GET['recieve_2'];
    $recieved_3 = $_GET['recieve_3'];

    //Do your processing here and insert it in the database
        //Insert Query OR Update Query (whatever)
    // after you have inserted you can get the response in
    // the <div> having id="myDiv" Or whatever you want
    // Suppose you have successfully inserted data then 
    $insertedDataBoolean = true;
    if($insertedDataBoolean){
        echo "Data: " . $recieved_1 . ", " . $recieved_2 . 
        " and " . $recieved_3 . " inserted successfully.";
    }
    else{
        echo "Data-insertion error.";
    }
?>