【问题标题】:Wordpress ajax not passing text variableWordpress ajax 不传递文本变量
【发布时间】:2021-06-02 05:24:54
【问题描述】:

我使用来自 wordpress 官方网站的 ajax 代码。如果我发送数字,一切正常,如果我发送一个它不发送的文本变量?

如果我用数字更改文本,一切正常并存储在数据库中,如果我输入文本,那么它会发送 0。

index.php

<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        var data = {
            'action': 'my_action',
            'whatever': 12345, 
            'notes': sometext, / Text is not sent???
            'courseid': 666555444
        };

        // 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);
        });
    });
    </script> <?php
}

函数.php


<?php 

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );
    $notes = intval( $_POST['notes'] );
    $course_id = intval( $_POST['courseid'] );

    $whatever += 10;

        echo $whatever;
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix. 'lms_enroll',
            [
                 'course' => $notes,
                 'student' => $whatever,
                 'course_ID' => $course_id,
            ]
         );

    wp_die(); // this is required to terminate immediately and return a proper response
}

【问题讨论】:

  • 问题:如果notes是一个字符串,你为什么要把它转换成一个整数?:$notes = intval( $_POST['notes'] );
  • 我只是从wordpress页面复制代码,谢谢,如何将评论标记为正确答案呵呵
  • 你不能:P 我会在下面留下一个答案,这样你就可以将其标记为已接受。

标签: ajax wordpress variables text send


【解决方案1】:

您的代码的问题是您将$_POST['notes'] 中的字符串转换为整数:

$notes = intval( $_POST['notes'] );

只需删除对intval 的调用即可按预期获取字符串:

$notes = $_POST['notes'];

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2018-06-30
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多