Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Как вставить php переменную в javascript


dava002
 Share

Recommended Posts

Добрый день! Подскажите пожалуйста как вставить php переменную в отдельный файл js на примере этого кода(код взят из product.tpl)

<script type="text/javascript"><!--
$('#review').delegate('.pagination a', 'click', function(e) {
	e.preventDefault();
	
    $('#review').fadeOut('slow');
        
    $('#review').load(this.href);
    
    $('#review').fadeIn('slow');
});         

$('#review').load('index.php?route=product/product/review&product_id=<?php echo $product_id; ?>');

$('#button-review').on('click', function() {
    $.ajax({
        url: 'index.php?route=product/product/write&product_id=<?php echo $product_id; ?>',
        type: 'post',
        dataType: 'json',
        data: $("#form-review").serialize(),
        beforeSend: function() {
            $('#button-review').button('loading');
        },
        complete: function() {
            $('#button-review').button('reset');
        },
        success: function(json) {
			$('.alert-success, .alert-danger').remove();
            
			if (json['error']) {
                $('#review').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
            }
            
            if (json['success']) {
                $('#review').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '</div>');
                                
                $('input[name=\'name\']').val('');
                $('textarea[name=\'text\']').val('');
                $('input[name=\'rating\']:checked').prop('checked', false);
            }
        }
    });
});
//--></script>

 

Edited by dava002
Link to comment
Share on other sites


36 минут назад, materialcart сказал:

нашел вот такой ответ 

Цитата

1) прописать в .htaccess разрешение на выполнение php в .js-файлах

 
Цитата:
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
 

2) поменять расширение файла с .js на .php и добавить в самое начало

 

<? header("Content-type: text/javascript"); ?>


3) .js-файл не трогать, а на странице генерировать необходимые переменные из php

С третьим пунктом не совсем понял что нужно сделать

Link to comment
Share on other sites


На самом деле много способов.

Можно к примеру сделать так:

require_once 'файл'; и взять переменную

Edited by Guest
Link to comment
Share on other sites

имеется в виду что за место вот этого кода, что я привел выше, хочу вставить подключение скрипта из отдельного файла, чтобы не засорять код, но в этом файле получается переменная php которая не работает в js. Может кто на платной основе это сделать?

Link to comment
Share on other sites


<button type="button" data-param="123"> ... </button>

 

$(id).on('click', function () {

  var my_param = this.data('param');

 

  console.log( my_param  );

  // 123

}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.