Jump to content

Передача JSON в UniHTMLFrame


Kast2k

Recommended Posts

Добрый день!

Хочу подключить flot графики к приложению.

HTML

		<div class="demo-container">
			<div id="placeholder" class="demo-placeholder"></div>
		</div>

AfterScript

	$(function() {

		if (typeof $.fn.prop != 'function') {
		    $.fn.prop = $.fn.attr;
		}

		var data = [{
			label: "United States",
			data: [[1990, 18.9], [1991, 18.7], [1992, 18.4], [1993, 19.3], [1994, 19.5], [1995, 19.3], [1996, 19.4], [1997, 20.2], [1998, 19.8], [1999, 19.9], [2000, 20.4], [2001, 20.1], [2002, 20.0], [2003, 19.8], [2004, 20.4]]
		}];

		var options = {
			series: {
				lines: {
					show: true
				},
				points: {
					show: false
				}
			},
			legend: {
				noColumns: 2
			},
			xaxis: {         
                autoScale: "exact",
				tickDecimals: 0
			},
			yaxis: {       
                autoScale: "loose",
                autoScaleMargin: 0.2,
				min: 0
			},
			zoom: {
				interactive: true
			},        
			selection: {
				mode: "x"
			}
		};
      
      var alreadyFetched = {};
      
		var placeholder = $("#placeholder");

		placeholder.bind("plotselected", function (event, ranges) {

			$("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));

			var zoom = true; // $("#zoom").prop("checked");

			if (zoom) {
				$.each(plot.getXAxes(), function(_, axis) {
					var opts = axis.options;
					opts.min = ranges.xaxis.from;
					opts.max = ranges.xaxis.to;
				});
				plot.setupGrid();
				plot.draw();
				plot.clearSelection();
			}
		});

		placeholder.bind("plotunselected", function (event) {
			$("#selection").text("");
		});

		var plot = $.plot(placeholder, data, options);
     
		$("#clearSelection").click(function () {
			plot.clearSelection();
		});      

		placeholder.bind("plotpan", function (event, plot) {
			var axes = plot.getAxes();
		});

		placeholder.bind("plotzoom", function (event, plot) {
			var axes = plot.getAxes();
		});
		// add zoom out button

      $.fn.unZoom = function (adata) {
			data = [];
			//alreadyFetched = {};

			$.plot("#placeholder", data, options);      
      
				data = adata; 
            console.log(data);
			//function onDataReceived(series) {
            console.log("Data received");
            //console.log(series);
				// Extract the first coordinate pair; jQuery has parsed it, so
				// the data is now just an ordinary JavaScript object

				//var firstcoordinate = "(" + series.data[0][0] + ", " + series.data[0][1] + ")";
				// Push the new data onto our existing data array

				//if (!alreadyFetched[series.label]) {
				//	alreadyFetched[series.label] = true;
				//	data.push(series);
				//}

				$.plot("#placeholder", data, options);
            console.log("PLOT OK");
		//	}
         
      //   console.log(window.parent.Ext.getCmp("_URLFrame"));
      //   console.log(window.parent.Ext.getCmp("_HTMLFrame"));
		//	$.ajax({
		//		url: Ext.getCmp("_HTMLFrame"),
      //      data: {data:data},
		//		type: "GET",
		//		dataType: "json",
		//		success: onDataReceived
		//	});            
                
      };

		$("<div class='button' style='right:20px;top:20px'>zoom out</div>")
			.appendTo(placeholder)
			.click(function (event) {
				event.preventDefault();
				plot.zoomOut();
			});

		// and add panning buttons

		function addArrow(dir, right, top, offset) {
			$("<img class='button' src='arrow-" + dir + ".gif' style='right:" + right + "px;top:" + top + "px'>")
				.appendTo(placeholder)
				.click(function (e) {
					e.preventDefault();
					plot.pan(offset);
				});
		}

		addArrow("left", 55, 60, { left: -100 });
		addArrow("right", 25, 60, { left: 100 });
		addArrow("up", 40, 45, { top: -100 });
		addArrow("down", 40, 75, { top: 100 });      

	});

Столкнулся с проблемой, что не могу нормально передать массив данных.

Пытаюсь так:

procedure TMainForm.UniButton1Click(Sender: TObject);
var
  s,so:string;
begin
  s:='{"label": "Europe (EU27)", "data": [[1999, 3.0], [2000, 8], [2001, 6.0], [2002, 1.2], [2003, 10.3]]}';
//  UniSession.AddJS('$.plot("#placeholder",['+s+'],'+so+')'); //ничего не происходит
  UniSession.AddJS('$.fn.unZoom(['+s+'])');
//  UniSession.AddJS('ajaxRequest('+MainForm.UniHTMLFrame1.JSName+',"$.fn.unZoom",['+s+'],false)'); //Synchronous XMLHttpRequest on the main thread is deprecated
end;

При загрузке страницы скрипт рисует тестовый набор данных (см. AfterScript).

Далее, через нажатие кнопки пытаюсь отправить из Unigui JSON данные.

Для приёма создал public function $.fn.unZoom. Она принимает массив, пишет в консоль и отображает график.

Но, при использовании функции масштабирования я вижу куски исходных графиков (созданных при загрузке скрипта).

Т.е. получается, что я создаю новый экземпляр объекта отображения?

Как правильно транслировать массив, подскажите, пожалуйста?

Basic jQuery-flot.zip

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...