2016-11-22 59 views
-1

我做了一个wordpress插件,其中我有几个div。 我想用下面的代码来获取div的内容。使用Ajax在wordpress数据库中存储html内容

var arhive = j("div.page2").html(); 
        console.log(arhive); 

工作正常,问题是当我试图将它发送到服务器来更新数据库与新的内容。

j.ajax({ 
    url: "send_data.php", 
    type: "post", 
    data: {html: arhive} , 
    success: function (response) { 
     // you will get response from your php page (what you echo or print)     
     console.log("success"); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.log(textStatus, errorThrown); 
    } 
}); 

这是我的send_data.php文件的内容。

$var = $_POST["html"]; 



$my_post = array(
     'ID'   => 4137, 
     'post_content' => '$var', 
); 

// Update the post into the database 
wp_update_post($my_post); 
echo "success"; 

我不知道为什么,但我得到500错误,数据不会存储任何想法可能会导致此?

This is the error I get

+0

什么问题?你有没有试过先编码'archive'?你有没有试过像'data:{html:archive}'格式正确地发送它? – Justinas

+0

你好,不,我想我设法做这一步,我的问题可能在PHP方面。在它上面工作。 –

+0

以上评论应该帮助您将格式正确的html代码格式化为变量“html”。在PHP上,您可以使用$ _POST [“html”]访问数据。并将其存储到数据库中,您可以检查此:http://www.w3schools.com/php/php_mysql_insert.asp –

回答

1

你可以设置一个WordPress的行动来处理Ajax调用,然后利用这些数据来将它们存储到数据库中:

WordPress的插件内的行动,存储发布的数据

add_action('wp_ajax_my_plugin_ajax_store', 'my_plugin_ajax_store_callback'); 

function my_plugin_ajax_store_callback() { 
    $whatever_data = $_POST['whatever']; 

    global $wpdb; // this is how you get access to the database 
    $wpdb->insert("wp_plugin_table", array(
     "whatever" => $whatever_data, 
    )); 

    echo 'Stored: '.$whatever_data; 

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

,您可以设置Ajax调用这样

jQuery(document).ready(function($) { 
    var data = { 
     'action': 'my_plugin_ajax_store', 
     '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); 
    }); 
}); 

有关wordpress ajax调用的更多信息,请参见AJAX in Plugins

相关问题