Я новичок в AJAX, и я просто пробовал некоторые примеры AJAX, но я получаю эту 500 Внутренняя ошибка сервера. Я ищу в Интернете решение, но ничего не получается. Тем не менее, если я изменить тип с POST на GET, он работает нормально.
контроллер:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class testingAjax extends CI_Controller
{
public function index()
{
$this->load->view('testingAjax_view');
}
public function getSomething()
{
$values = $this->input->post('testing');
echo $values;
}
}
JS скрипт
$(document).ready(
function ()
{
$('#callBackBtn').click(function()
{
jQuery.ajax({
type: "POST",
url: "testingAjax/getSomething",
data: {testing: "testing"},
success: function(data) {
$('#responseText').val(data);
},
error: function(xhr, text_status, error_thrown){
alert(error_thrown);
}
})
});
}
);
Посмотреть
<body>
<h3>Testing Ajax</h3>
<div class="entry-wrapper">
<input type="text" id="input_text">
<input type="button" value="Ajax Call Back" id="callBackBtn"/>
</div>
<div class="response_wrapper">
<textarea id="responseText"></textarea>
</div>
</body>
Я запускаю это на xammp. Ниже приведены журналы ошибок Apache (не уверен, полезны они или нет)
[Wed May 13 00:31:53.251642 2015] [core:notice] [pid 25716:tid 456] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Wed May 13 00:31:53.257646 2015] [mpm_winnt:notice] [pid 25716:tid 456] AH00418: Parent: Created child process 25724
[Wed May 13 00:31:57.895294 2015] [ssl:warn] [pid 25724:tid 460] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Wed May 13 00:31:59.065692 2015] [ssl:warn] [pid 25724:tid 460] AH01909: www.example.com:443:0 server certificate does NOT include an ID which matches the server name
[Wed May 13 00:31:59.205786 2015] [mpm_winnt:notice] [pid 25724:tid 460] AH00354: Child: Starting 150 worker threads.
Firebug показал ошибку:
POST http://localhost/ias/testingAjax/getSomething
500 Internal Server Error
30ms
Попробуй с
url:"/testingAjax/getSomething".
Для вызова ajax метод по умолчанию GET
а ты не публиковал form
или любое значение для сервера, просто сделать ajax-вызов по нажатию кнопки, поэтому это может сработать !!! когда вы изменили тип метода с POST
в GET
но прежде всего я думаю, что вы должны исправить url
Метод (по умолчанию: «GET»)
Тип: String Метод HTTP, используемый для
запрос (например, «POST», «GET», «PUT»)
увидеть больше здесь http://api.jquery.com/jquery.ajax/
Я создал свежую копию вашей работы, а здесь простую, которой вы могли бы следовать.
Во-первых, правильно настроить ваш проект.
Сначала я создаю файл .htaccess в корневой папке той же директории, что и index.php, чтобы создать красивый URL
Вот простой файл содержимого .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</IfModule>
И вам нужно включить расширение / настройку mod_rewrite вашего сервера
Вы можете включить его, найдя appache / httpd.conf
и найдите «LoadModule rewrite_module modules / mod_rewrite.so»
удалите # и сохраните и перезапустите приложение.
Следующим шагом является включение помощника URL
на
приложение / Config / autoload.php
$autoload['helper'] = array('url');
использовать url helper, созданный CI;
Увидеть URL HELPER
Далее нужно настроить контроллер по умолчанию, чтобы сделать это
приложение / Config / routes.php
$route['default_controller'] = 'testingAjax';
Контроллер testingAjax.php
<?php
class testingAjax extends CI_Controller
{
public function index()
{
$this->load->view('testingAjax_view');
}
public function getSomething()
{
$values = $this->input->post('testing');
echo $values;
}
}
Представление testingAjax_view.php
<html>
<head>
<script type="text/javascript">
// get the base url of the project
var BASE_URL = "<?php echo base_url(); ?>";
</script>
</head>
<body>
<h3>Testing Ajax</h3>
<div class="entry-wrapper">
<input type="text" id="input_text">
<input type="button" value="Ajax Call Back" id="callBackBtn"/>
</div>
<div class="response_wrapper">
<textarea id="responseText"></textarea>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#callBackBtn').on('click', function(){
$.ajax({
type: "POST",
url: BASE_URL + "testingAjax/getSomething",
data: {testing: $('#input_text').val()},
success: function(data) {
$('#responseText').val(data);
},
error: function(xhr, text_status, error_thrown){
alert(error_thrown);
}
});
// But if you cannot setup the pretty url
// using .htaccess
// then you can use the
// BASE_URL+ "index.php/" + "testingAjax/getSomething
});
});
</script>
</body>
</html>
Просто поместите это в ваш файл .htaccess, который находится в вашем корневом каталоге:
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
Замечания:
RewriteBase /
здесь важно