将当前页面的 php 变量传递给 XMLHttpRequest2(即 $user_id)

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

我想弄清楚当前页面的 php $var 是否可以传递给 XMLHttpRequest2。正在调用的文件位于 /assets/js 目录中的视图(当前 php 页面所在的位置)文件夹之外。我也在使用 CodeIgniter。尝试传递 $user_id 以用于 XMLHttpRequest2 请求文件中的 SQL 查询。

publication_call.php(当前文件)

  <form>
    <input type="hidden" id="someid" value="<?= $idz ?>"/>
    <?php
      echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
      echo form_label('Matching<br>Publications:');
    ?>
    <select name="matched_pub" id="matched_pub"></select>
  </form>

<script>
  jQuery(function($){
    //still want to bind the change event
    $('#matched_pub').bind('change', function(){
        $('#title').val($('#matched_pub option:selected').text());
    });
    $('#validation').keyup(function() {
        showKeywords( $('#validation').val() );
        document.getElementById('matched_pub').style.display='block';
    });
  });
</script>


  <script>
    function showKeywords(str)
    {

        if (document.getElementById("matched_pub")) {

            if (str.length==0)
            {
                document.getElementById("matched_pub").innerHTML="";
                document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                return;
            }
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp2=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp2.onreadystatechange=function()
            {
                if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
                {
                    document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                }
            }
            xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
            xmlhttp2.send();

        }

    }
</script>

searchwords.php(requested/external 文件)

  <?php

$user   = 'root';
$pass   = 'root';
$db     = 'hey_there';
$host   = 'localhost';

$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);

//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
    echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);

//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
    FROM teacher_publications
    JOIN users ON teacher_publications.user_id = users.id
    WHERE keywords IS NOT NULL 
    AND pub_title IS NOT NULL
    AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';

//loop through all words in string
foreach($queryWords as $queryWord) {
    $queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;

$resultServices = mysql_query($queryServices);
$services ='';

if(mysql_num_rows($resultServices) > 0){    
    while($rowServices = mysql_fetch_assoc($resultServices)) {
        $services .= '<option  value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
    }
}



if( mysql_num_rows($resultServices) == 0 )
{
    echo '<option  value="">Your search failed to find any matching results.</option>';
}
else
{
    echo '' . $services . '';
}

/* ============================== 编辑代码 ============================== */

publication_call.php(当前文件)

<input type="hidden" id="someid" value="<?= $user_id ?>"/>

<script>
    function showKeywords(str)
    {

        if (document.getElementById("matched_pub")) {


            if (str.length==0)
            {
                document.getElementById("someid");
                document.getElementById("matched_pub").innerHTML="";
                document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                return;
            }
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp2=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp2.onreadystatechange=function()
            {
                if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
                {
                    document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
                }
            }
            xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
            // xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
            xmlhttp2.send();

        }

    }
</script>

searchwords.php(requested/external 文件)

 $usr = $_GET["user_id"];

 $query = "SELECT DISTINCT(pub_title)
           FROM teacher_publications
           JOIN users ON teacher_publications.user_id = users.id
           WHERE keywords IS NOT NULL 
           AND pub_title IS NOT NULL
           AND teacher_publications.user_id = ".$usr."

";

您可以将 $user_id 放在隐藏的输入字段中,并使用 Javascript,读取它的值以在您的 Ajax 请求中使用

你可以这样做:

<input type="hidden" id="someid" value="<?= $user_id ?>

然后在你完成之后,你可以通过这样做来获得价值:

document.getElementById('someid'); 使用纯 Javascript 或 $('#someid').value(); 如果您使用 jquery

这将为您获取用户 ID 值,然后您可以在请求中使用该值。

像这样:

xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true); 将您当前的 xmlhttp2.open 替换为上面的那个 现在您可以在请求的文件中访问 $_GET['user_id'] 中用户 ID 的值。