简体   繁体   English

调用PHP函数并将值返回给Javascript

[英]Call PHP function and return value to Javascript

I am working with Wordpress and the Javascript will insert text in to the editor on the edit post. 我正在使用WordpressJavascript将文本插入到编辑帖子中的编辑器中。

I have two files, one is the js and another one is the PHP file. 我有两个文件,一个是js ,另一个是PHP文件。 I want to call the PHP function to return the database value to the Javascript . 我想调用PHP函数以将数据库值返回给Javascript

What I am doing: 我在做什么:

I have [value - X] points. 我有[值-X]分。 //The Javascript will insert this into the editor. // JavaScript会将其插入到编辑器中。 [value - x] is the value which return from the PHP function [value-x]是从PHP函数返回的值

Here is my JavaScript : 这是我的JavaScript

   onsubmit: function( e ) 
{
var str = '';                                                                    
if(e.data.friend_cb ) 
{                                                                            
    str += 'I have [value - X] points. <br><br/>';
}

editor.insertContent(str);



jQuery.ajax({
    url: 'http://localhost:8080/wordpress/wp-content/plugins/databaseConnection.php',
    type: 'POST',
    data: {functionname: 'getX', condition_code: condition_code},
        error:function(data)
        {
            alert("failed");
            console.log(data);
        },
        success: function(data) 
        {
            alert("success");                                                                                
            console.log(data); // Inspect this in your console
        }
});

And here is the PHP function: 这是PHP函数:

if( !isset($_POST['condition_code']) ) 
 {
      $error .= 'No function no_friend!';          
      $condition_code = $_POST['condition_code'];
 }

    $functionName  = $_POST['functionname'];
          // $functionName = 'add_bonus_point';
    switch($functionName) {
        case 'set_no_friend':  


             //Check did it pass the functionName
            if( !isset($_POST['functionname']))
                  $error .= 'No function name!'; 
            else
                 $errorBool = false;
            break;
        case 'try_insert':
            getX();
            break;
        }


 function getX()
 {
     $x = 0;
     //Connect to database, get X value.
     return $x;

 }

How can I get the value X? 如何获得值X?

Thx a lot. 多谢。

First thing first. 首先是第一件事。 If you are working on wordpress , you should call ajax in wordpress way 如果您正在使用wordpress ,则应以wordpress的方式调用ajax

See : https://codex.wordpress.org/AJAX_in_Plugins 参见: https : //codex.wordpress.org/AJAX_in_Plugins

Your javascript should be 您的JavaScript应该是

onsubmit: function( e ) {
    var str = '';                                                                    
    if(e.data.friend_cb ) {                                                                            
        str += 'I have [value - X] points. <br><br/>';
    }

    editor.insertContent(str);

    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action:'my_ajax_function',
            functionname: 'getX', 
            condition_code: condition_code
        },
        error:function(data){
            alert("failed");
            console.log(data);
        },
        success: function(data) {
            alert("success");                                                                                
            console.log(data); // Inspect this in your console
        }
    });
}

Your PHP code should be 您的PHP代码应为

add_action( 'wp_ajax_my_ajax_function', 'my_ajax_function' );
add_action( 'wp_ajax_nopriv_my_ajax_function', 'my_ajax_function' );

function my_ajax_function(){
    if( !isset($_POST['condition_code']) ) {
          $error .= 'No function no_friend!';          
          $condition_code = $_POST['condition_code'];
    }

    $functionName  = $_POST['functionname'];
          // $functionName = 'add_bonus_point';
    switch($functionName) {
        case 'set_no_friend':  


             //Check did it pass the functionName
            if( !isset($_POST['functionname']))
                  $error .= 'No function name!'; 
            else
                 $errorBool = false;
            break;
        case 'try_insert':
            getX();
            break;
    }
}

function getX(){
     // access global variable $wpdb database connection object
     global $wpdb; 
     $x = 0;
     //Connect to database, get X value.
     return $x;
}

You can put json array for get data. 您可以将json数组用于获取数据。 Please write below code. 请写下面的代码。

function getX()
 {
     $x = 0;
     //Connect to database, get X value.
     $data = array(
            "x"     => 0
          );
      echo json_encode($data);

 }

And Javascript code like below. 和下面的Javascript代码一样。

jQuery.ajax({
    url: 'http://localhost:8080/wordpress/wp-content/plugins/databaseConnection.php',
    type: 'POST',
    data: {functionname: 'getX', condition_code: condition_code},
        error:function(data)
        {
            alert("failed");
            console.log(data);
        },
        success: function(data) 
        {
            var obj = jQuery.parseJSON(data);
            alert( obj.x );

            console.log(obj); // Inspect this in your console
        }
});

for example 例如

<script type="text/javascript">
  var phpVariable = "<?php
  $x = getX();
  echo $x;
  ?>";
</script>

store the php value into a javascript variable 1st, then use it in your javascript. 将php值存储到javascript变量1st中,然后在javascript中使用它。 Just make sure that this variable is declared and assigned value to before the script that uses it. 只要确保在使用该变量的脚本之前声明了该变量并将其赋值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM