空格后,Javascript变量被切断了

时间:2012-08-02 00:18:13

标签: php javascript string variables

我有一个PHP页面,我正在使用JavaScript来更新基于MySQL结果的下拉列表。我的问题是,当我通过JavaScript变量传递客户名称时,它会在第一个空格处切断。例如:“Home Depot”将显示为“Home”或“Home Store”显示为“The”。为了执行正确的查询,我希望传递整个字符串。

以下是我的表格中的相关代码:

    function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
      }


    function getCustCont(cID)
    {
    var strURL="Includes/cdd.php?custid="+cID;
    var req = getXMLHTTP();
    if (req)
    {
      req.onreadystatechange = function()
      {
       if (req.readyState == 4)
       {
     // only if "OK"
     if (req.status == 200)
          {
        document.getElementById('Contdiv').innerHTML=req.responseText;
     } else {
        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
      }
        }
       }
    req.open("GET", strURL, true);
    req.send(null);
    }

//VARIABLES DEFINED AND START OF FORM

    <td width="60%">

    <select name="Customer" onchange="getCustCont(this.value)">
    <option value="SAC">Select Customer</option>
    <?php
    $i=0;
    while ($i < $num) {
    $Name=mysql_result($result,$i,"Name");

    echo "<option value=$Name>$Name</option>";
    $i++;
    }       
    ?>  

    </select>
    </td>

cdd.php文件包含以下内容:

  <? 
    $Cust_ID = $_GET['custid'];
    include('../Includes/TrackingDB.php');

    mysql_connect($dbhost,$dbuser,$dbpass) or die('Error connecting to mysql');
    mysql_select_db($dbdb) or die('Error connecting to database');

    $query="SELECT t1.ContName FROM Cust_Contacts t1 INNER JOIN Customer_Listing t2 ON t1.Cust_ID = t1.Cust_ID WHERE t2.Name = '$Cust_ID'";
    $result=mysql_query($query);

    mysql_close();

    echo var_dump($Cust_ID); //I added this solely for the purposes of trouble shooting this issue. This is where I am seeing the truncated string.

    ?>
    <select name="Cust_Buyer" onchange="getCity(<?=$country?>,this.value)">
    <? while($row=mysql_fetch_array($result)) { ?>
    <option value="<?=$row['ContName']?>"><?=$row['ContName']?></option>
    <? } ?>
    </select>

同样,在cdd.php文件中,字符串在空格处截断。

1 个答案:

答案 0 :(得分:2)

编码 cID

var strURL="Includes/cdd.php?custid="+encodeURIComponent(cID);

并用引号括起来:

echo "<option value='$Name'>$Name</option>";
相关问题