在一个页面上发送和打印PHP数组结果?

时间:2011-09-14 12:18:41

标签: php javascript mootools

我是PHP初学者,今天我开始学习Mootools。我正在尝试使用自动完成搜索框,在您提交表单后发送一个数组。您可以键入多个名称并搜索所有名称。

我要做的是在mootools中获取该数组,将其发送到PHP并显示结果而不离开页面。

Here is the original file

// Autocomplete initialization
var t4 = new TextboxList('form_tags_input_3', {unique: true, plugins: {autocomplete: {}}});

// sample data loading with json, but can be jsonp, local, etc. 
// the only requirement is that you call setValues with an array of this format:
// [
//  [id, bit_plaintext (on which search is performed), bit_html (optional, otherwise plain_text is used), autocomplete_html (html for the item displayed in the autocomplete suggestions dropdown)]
// ]
// read autocomplete.php for a JSON response example

t4.container.addClass('textboxlist-loading');               
new Request.JSON({url: 'autocomplete.php', onSuccess: function(r) {
  t4.plugins['autocomplete'].setValues(r);
  t4.container.removeClass('textboxlist-loading');
}}).send();     

这是autocomplete.php

$response = array();
$names = array('Some name', 'Some name 2', 'etc');

// make sure they're sorted alphabetically, for binary search tests
sort($names);

foreach ($names as $i => $name)
{
    $filename = str_replace(' ', '', strtolower($name));
    $response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);
}

header('Content-type: application/json');
echo json_encode($response);

Submit.php

<?php
print_r($_POST);
?>

And here is what I did

我的php:

<?php
$result['msg'] = print_r($_POST);

echo json_encode($result);
?>

以下是我在index2.php文件中所做的更改:

<input type="submit" name="submitform" value="Submit" id="submitform" />
<p id="response"></p>  

$('#submitform').addEvent('click', function(){

  new Request.JSON({  
        url: "inc/php/json.php",  
        onSuccess: function(response){  

        $('response').set('html',+data.result);  

        }  
    }).get($('findnames')); 


});

当你按提交时,没有任何反应,所以很明显我在某个地方犯了一个我似乎无法弄清楚的错误。

1 个答案:

答案 0 :(得分:0)

$result['msg'] = print_r($_POST);

你不能这样做,print_r直接打印数组内容到页面,所以你不能将它存储在变量中。

也许你会用这个:

<input type="button" onclick="SomeFunction(); name="submitform" value="Submit" id="submitform" />

只需将SomeFunction();更改为其他内容。

编辑: 我检查了Chrome错误控制台,以及它的内容:

Uncaught TypeError: Cannot call method 'addEvent' of null

所以#submitform似乎在某些原因上无效。请尝试我的功能,让它像它应该的那样工作。