使用AJAX将javascript数组传输到PHP


Transfer javascript array to PHP using AJAX

我已经收到帮助这里和stackoverflow使邀请功能。在基于AJAX的搜索框中,可以邀请团队。当搜索一个球队,找到它,然后选择它-球队将被存储在一个数组中。但是,我需要PHP中数组中的数据。

我的问题:我可以使用AJAX将javascript数组转移到PHP吗?代码可以在下面看到。AJAX部分使用jQuery。

//AJAX based search
var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j("#search_results").slideUp();
    $j("#button_find").click(function(event){
        event.preventDefault();
        search_ajax_way();
    });
    $j("#search_query").keyup(function(event){
        event.preventDefault();
        search_ajax_way();
    });
});
function search_ajax_way(){
    $j("#search_results").show();
    var search_this=$j("#search_query").val();
    $j.post("search_team.php", {searchit : search_this}, function(data){
        $j("#display_results").html(data);
    })
}
// <----- AJAX search ends ------>
//Add-remove teams
//Functional object for team
var Team = function (id, name) {
    this.name = name;
    this.id = id;
}
//Array which will contain teams
var TeamList = [];
//Checking if the team is already added
function containsTeam(id) {
    for (var i = 0; i < TeamList.length; i++) {
        if (TeamList[i].id == id) {
            return true;
        }
    }
    return false;
}
// Removed team by onclick-event
function removeTeam(id) {
    for (var i = 0; i < TeamList.length; i++) {
        if (TeamList[i].id == id) {
            TeamList.splice(i, 1);
            document.getElementById('teams').removeChild(document.getElementById('ta'+id));
        }
    }
}
function addTeam(tid) {
    // Grab the input value
    var teamName = document.getElementById(tid).innerHTML;
    var teamID = document.getElementById(tid).id;
    // If empty value
    if(!teamName || !teamID) {
        alert('An error occured.');
    } else {
        if(containsTeam(teamID) == false) {
            TeamList.push(new Team(teamID, teamName));
            // Create the teams with the value as innerHTML
            var div = document.createElement('div');
            div.className = 'team-to-invite';
            div.setAttribute('onclick', 'removeTeam('+teamID+')');
            div.onclick = function() { removeTeam(teamID) };
            div.id = 'ta' + teamID;
            div.innerHTML = teamName;
            // Append it and attach the event (via onclick)
            var teams = document.querySelector('#teams').getElementsByTagName('div');
            document.querySelector('#teams').appendChild(div);
        }
    }
    return false;
}

团队存储在TeamList()中。

目前最好的方法是数组编码为字符串,这是您可以POST到PHP脚本的唯一格式。

JSON编码是目前在互联网上发送此类数据最流行的标准。下面是一些编码数据的示例:
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

一般来说,您将使用jQuery的JSON编码对数组进行编码,将这些数据发布到PHP脚本中,然后在PHP端对其进行解码。

用jQuery发布一个数组

var dataToSend = { 
    data: TeamList
};
jQuery.ajax({
    type: 'POST',
    url: "myPhp.php",
    data: JSON.stringify(dataToSend),
    dataType: "json",
    success: function(data){ alert(data); }
});

PHP解码JSON

<?php
$foo = file_get_contents("php://input");
$decoded = json_decode($foo, true);
var_dump($decoded); //Print out the data
$myArray = $foo => data;

我可以将javascript数组转移到PHP中吗

你只能将字符串从执行javascript的浏览器传输到执行php的服务器。但是有一些公认的字符串格式,例如json,可以转换为数组等。