我正在尝试做一些基本的东西,但我的PHP代码似乎没有被调用。
我有一个带onclick
事件的按钮,指向js函数
<button type="button" onclick="tryphp()">go!</button>
,这是在我的index.php文件中。
然后我在我的js文件中有一个名为js的子文件夹,其功能如下
function tryphp() {
jQuery.ajax({
url: 'php/try.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert('success!!!!');
}
});
}
最后,我在try.php中有另一个子文件夹“php”
<?php
echo 'hello';
?>
我希望按钮能够“成功!!!!”点击但没有任何反应。 我想弄清楚错误是否在ajax调用的“url”参数中?
文件结构如下
/main/index.php
/main/js/file.js
/main/php/try.php
任何帮助都会很棒!
最后但并非最不重要的是,我的functions.php文件如下
<?php
function newtheme_script_enqueue() {
wp_enqueue_style('style1', get_template_directory_uri() . '/css/newtheme.css', array(), '1.0.0', 'all');
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array(), '1.0.0', TRUE);
wp_enqueue_script('script1',get_template_directory_uri() . '/js/jquery.js', array(), '1.0.0', TRUE);
}
add_action('wp_enqueue_scripts','newtheme_script_enqueue');
并且在jquery.js里面我已经下载了jquery的压缩版本。
提前感谢!
----------- ------------ UPDATE 解决!
有2个错误:
-i未在脚本入队中指定依赖项
wp_enqueue_script('script1',get_template_directory_uri() . '/js/newtheme.js', array('jquery'), '1.0.0', TRUE);
- php文件的路径缺少“模板目录”部分
谢谢大家!
答案 0 :(得分:0)
首先,您必须知道 Wordpress集成ajax
以及。
在文件functions.php
上,您必须具有触发结果的功能才能进行ajax调用
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
在javascript
文件上应该有类似的内容:
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
请参阅此link的插件,该插件是针对插件制作的,但也适用于主题。
答案 1 :(得分:0)
如果你提出了很多ajax请求,你可能想要使用这样的东西来帮助发现问题:
jQuery.ajax({
url: 'php/try.php',
dataType: 'text',
success: function (response) {
console.log('Success: ' + response);
},
error: function (x) {
//loop though error response
$.each(x, function(y, z){
console.log('Error: ' + y + ' ' + z);
});
},
});
如果你的php文件中某处有错误,你应该在console.log中的“Success”响应之后看到它。如果您的网址不正确,您应该会在“错误”响应中的某处看到错误 - 通常是在响应结束时。 (除非您喜欢浏览器警报的声音,否则我会将您的响应发送到console.log,因为错误响应会产生相当多的警报。)