开发者

Passing PHP variable [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? (19 answers) Closed 8 years ago.

I have a PHP array:

foreach($xpath->query('//a') as $element) {
     $linklabel[] = $element->textContent;
     $link[] = $element->getAttribute("href");
     $i=$i+1;
}

I also have an HTML form:

<form name="keypad" id="form"  onSubmit="return pass(this)">
<input type="text" size="100%"开发者_JS百科; length="25" value="" name="lcd">
<input type="button" value=" 1 " name="one" onClick="this.form.lcd.value+=this.value">
<input type="button" value=" 2 " name="two" onClick="this.form.lcd.value+=this.value">
<input type="button" value=" 0 " name="zero" onClick="this.form.lcd.value+=this.value">
<input type="submit" name="Submit" id="Submit" value="Go" >
</form>

How can I write the onSubmit function pass() that takes the values from the keypad and sends the corresponding $link[] value to browse.php. For example, if $link[20]='google.com'; , I want to pass $link[20] to browse.php if user enters 20 in the keypad and presses Go.


You'll need to output the PHP array in a way the Javascript can interpret, like as a Javascript array:

<?php
echo "<script type=\"text/javascript\">\n";
echo "var links = [";
foreach($links as $link)
    echo "'$link', ";
echo "];\n";
echo "</script>\n";
?>

You also need an element in the form the function can set:

<input type="hidden" name="url">

Then your Javascript function can index into the array and modify the form element:

function pass() {
    id = parseInt(document.getElementsByTagName('form')[0].lcd.value, 10);
    document.getElementsByTagName('form')[0].url.value = links[id];
}

Your button values have spaces around them for some reason; they should just be the number, or lcd.value will end up with spaces throughout it. If you want the buttons to have padding use CSS.

Finally, you need to post the form if you're going to check $_POST on the other end, so change the tag to:

<form name="keypad" id="form" method="post" onSubmit="return pass()">

You can also just use $_GET on the target page

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜