使用AJAX将变量发送到php

时间:2011-07-12 08:23:19

标签: php javascript ajax xmlhttprequest

如何在此代码中将rowNumber变量发送到dataSource php文件?

function getData(dataSource, divID,rowNumber) 
{ 

if(XMLHttpRequestObject)
{
    var obj = document.getElementById(divID); 
    XMLHttpRequestObject.open("GET", dataSource); 
    XMLHttpRequestObject.onreadystatechange = function() 
        { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) 
            { 
                obj.value = XMLHttpRequestObject.responseText; 
            } 
        } 

        XMLHttpRequestObject.send(null); 
    }
}

PHP文件(数据源):

<?php
  //mysql connection
  $result = mysql_query( 'CALL view_polls(`rowNumber`);' );
  $row=mysql_fetch_array($result);
  echo $row['title'];
?>

2 个答案:

答案 0 :(得分:5)

JavaScript中的

XMLHttpRequestObject.open("GET", dataSource + '?rowNumber=' + rowNumber);
PHP中的

$result = mysql_query( 'CALL view_polls(`' . $_GET['rowNumber'] . '`);' );

答案 1 :(得分:2)

function getData(dataSource, divID,rowNumber) 
{ 

if(XMLHttpRequestObject)
{
    var obj = document.getElementById(divID); 
    XMLHttpRequestObject.open("GET", dataSource + "?rownumber=" + rowNumber); 
    XMLHttpRequestObject.onreadystatechange = function() 
        { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) 
            { 
                obj.value = XMLHttpRequestObject.responseText; 
            } 
        } 

        XMLHttpRequestObject.send(null); 
    }
}

PHP:

<?php
  if (isset($_GET['rownumber']) && is_numeric($_GET['rownumber'])) {
        $rowNumber = $_GET['rownumber'];
        //mysql connection
        $result = mysql_query( 'CALL view_polls(`' . $rowNumber . '`);' );
        $row=mysql_fetch_array($result);
        echo $row['title'];
  }
  else {
        echo "Error";
  }
?>