0

i m writing a script using javascript ajax request and php.. i make an ajax call to verify that a user is recognised or not and according to the "response" i want to make a second ajax request either letting him either make his choices if his is already a registered user, or display the already submitted choices

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    var script = document.createElement('script');
        script.innerHTML = xmlhttp.responseText;
        document.getElementsByTagName('head')[0].appendChild(script);
        removeOnclick();
        //document.getElementById("txtHint").innerHTML=
    }
  }
xmlhttp.open("GET","submit_votes.php?q="+str+string,true);
xmlhttp.send();
}

on my php side

i have these lines in case he is recognised

if (mysqli_num_rows($result) > 0) {

while($row = mysqli_fetch_array($result))
  {
    echo "document.getElementById('".$row['option1']."').className += ' colour1';";
    ....
}

but if he is not recognised i have set this check

if (!isset($_GET['option1'])){ //option1 is one of the parameters i pass through "string"
    echo "nodata";
    }

the first call is made passing only the string is set ""

 q="+str+string

while on the second call string is set as option1=A&option2=B etc etc...

the issue is, that i try to alert the xmlhttpresponse to check if the response has been altered, but the resposne remains the same..for instance if he is not recognised i ll get in both responses "nodata" while if i refresh the page and he is recognised, i ll get the document.getElementById('".$row['option1']."').className += ' colour1'; response..

the reason i need this is because i want this part

    var script = document.createElement('script');
        script.innerHTML = xmlhttp.responseText;
        document.getElementsByTagName('head')[0].appendChild(script);
        removeOnclick();
        //document.getElementById("txtHint").innerHTML=

to be executed only if he is recognised..

4

1 回答 1

0

在考虑了 moonwave99 的评论之后,我最终得到了一个不同的解决方案..

首先我发现,条件检查失败,因为在 responseText 中有一个额外的空格..所以最初我使用

xmlhttp.responseText.trim();

为了删除不需要的字符......但我仍然感觉不对,因为我将 js 代码作为字符串从 php 传递回 js .. 我决定使用 json .. 所以在 php 方面,我使用json编码

$options = array($row['option1'],$row['option2'],$row['option3'],$row['option4'],$row['option5'],$row['option6'],
                    $row['option7'],
                    $row['option8'],
                    $row['option9'],
                    $row['option10']
                    );
echo json_encode($options);

在我使用的javascript方面

    var jsObject = JSON.parse(xmlhttp.responseText);
    var jslength = jsObject.length;
    for (i=0; i<jslength; i++){
        document.getElementById(jsObject[i]).className += ' colour';
    }
于 2013-04-25T07:56:05.197 回答